Java 类java.util.concurrent.TimeUnit 实例源码

项目:ditb    文件:TestIdLock.java   
@Test
public void testMultipleClients() throws Exception {
  ExecutorService exec = Executors.newFixedThreadPool(NUM_THREADS);
  try {
    ExecutorCompletionService<Boolean> ecs =
        new ExecutorCompletionService<Boolean>(exec);
    for (int i = 0; i < NUM_THREADS; ++i)
      ecs.submit(new IdLockTestThread("client_" + i));
    for (int i = 0; i < NUM_THREADS; ++i) {
      Future<Boolean> result = ecs.take();
      assertTrue(result.get());
    }
    idLock.assertMapEmpty();
  } finally {
    exec.shutdown();
    exec.awaitTermination(5000, TimeUnit.MILLISECONDS);
  }
}
项目:auto-scale-java    文件:OKHttpUtil.java   
public static synchronized OKHttpUtil getInstance(){
        ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
                .tlsVersions(TlsVersion.TLS_1_2)
                .cipherSuites(
                        CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
                        CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
                        CipherSuite.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256)
                .build();
        client = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
//                .connectionSpecs(Collections.singletonList(spec)).
                .addInterceptor(new RetryInterceptor())
                .build();
        return INSTANCE;
    }
项目:orange-mathoms-logging    文件:ThreadPoolTaskExecutorWithMdcPropagationTest.java   
@Test
    public void mdc_context_should_be_propagated() throws InterruptedException, ExecutionException {
//      ExecutorService executorService = Executors.newFixedThreadPool(4);
        ExecutorService executorService = new ThreadPoolTaskExecutorWithMdcPropagation(4, 4, 50, TimeUnit.MILLISECONDS, new LinkedBlockingQueue());
        List<Future<String>> futures = new ArrayList<Future<String>>();
        List<String> expectedTasks = new ArrayList<>();
        for(int i=0; i<100; i++) {
            MDC.put("requestId", "task"+i);
            expectedTasks.add("task"+i);
            futures.add(executorService.submit(new Callable<String>() {
                @Override
                public String call() throws Exception {
                    Thread.sleep(100);
                    return MDC.get("requestId");
                }
            }));
        }

        for(Future<String> f : futures) {
            String t = f.get();
            if(!expectedTasks.remove(t)) {
                Assert.fail("Unexpected task: "+t);
            }
        }
        if(!expectedTasks.isEmpty()) {
            Assert.fail("Expected tasks not returned: "+expectedTasks);
        }
    }
项目:config    文件:SimpleConfigPropertyTest.java   
@Test
public void testValueParserFailingOnReload() throws Exception {
  when(configSource.loadConfig())
      .thenReturn(toConfigProps(mapBuilder().put("int", "1").build()))
      .thenReturn(toConfigProps(mapBuilder().put("int", "not an int").build()));
  ConfigRegistryImpl configRegistry = newConfigRegistry(configSource);

  IntConfigProperty intProperty = configRegistry.intProperty("int");
  intProperty.addValidator(Objects::nonNull);
  intProperty.addValidator(i -> i >= 1);
  intProperty.addCallback((i1, i2) -> sideEffect.apply(i1, i2));

  assertTrue(intProperty.value().isPresent());
  assertEquals(1, (int) intProperty.value().get());

  TimeUnit.MILLISECONDS.sleep(WAIT_FOR_RELOAD_PERIOD_MILLIS);

  assertTrue(intProperty.value().isPresent());
  assertEquals(1, (int) intProperty.value().get());
  verify(sideEffect, never()).apply(any(), any());
}
项目:lams    文件:SimpleNonceManager.java   
private boolean addInvalidNonce(final Nonce nonce, final XnioExecutor executor) {
    long now = System.currentTimeMillis();
    long invalidBefore = now - firstUseTimeOut;

    long timeTillInvalid = nonce.timeStamp - invalidBefore;
    if (timeTillInvalid > 0) {
        if (invalidNonces.add(nonce.nonce)) {
            executor.executeAfter(new InvalidNonceCleaner(nonce.nonce), timeTillInvalid, TimeUnit.MILLISECONDS);
            return true;
        } else {
            return false;
        }
    } else {
        // So close to expiring any record of this nonce being used could have been cleared so
        // don't take a chance and just say no.
        return false;
    }
}
项目:Dalaran    文件:XApiServiceHelper.java   
public static   <T> T create(Class<T> c, String url) {
    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    OkHttpClient client = new OkHttpClient.Builder()
            .addInterceptor(interceptor)//日志拦截器
            .addNetworkInterceptor(new CommonInterceptor())//网络拦截器,进行重定向等操作
            .connectTimeout(10, TimeUnit.SECONDS)//设置连接超时
            .build();
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(url)
            .addConverterFactory(XJsonConverterFactory.create())//json数据转换
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())//将Callable接口转换成Observable接口
            .client(client)//网络请求客户端为okhttp
            .build();
    return retrofit.create(c);
}
项目:drinkwater-java    文件:Main.java   
protected void waitUntilCompleted() {
    while (!completed.get()) {
        try {
            if (duration > 0) {
                TimeUnit unit = getTimeUnit();
                LOG.info("Waiting for: " + duration + " " + unit);
                latch.await(duration, unit);
                exitCode.compareAndSet(UNINITIALIZED_EXIT_CODE, durationHitExitCode);
                completed.set(true);
            } else {
                latch.await();
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}
项目:GitHub    文件:CacheTest.java   
@Test public void requestPragmaNoCache() throws Exception {
  server.enqueue(new MockResponse()
      .addHeader("Last-Modified: " + formatDate(-120, TimeUnit.SECONDS))
      .addHeader("Date: " + formatDate(0, TimeUnit.SECONDS))
      .addHeader("Cache-Control: max-age=60")
      .setBody("A"));
  server.enqueue(new MockResponse()
      .setBody("B"));

  HttpUrl url = server.url("/");
  assertEquals("A", get(url).body().string());
  Request request = new Request.Builder()
      .url(url)
      .header("Pragma", "no-cache")
      .build();
  Response response = client.newCall(request).execute();
  assertEquals("B", response.body().string());
}
项目:iTAP-controller    文件:SwitchResourceBase.java   
protected OFFeaturesReply getSwitchFeaturesReply(DatapathId switchId) {
    IOFSwitchService switchService =
            (IOFSwitchService) getContext().getAttributes().
            get(IOFSwitchService.class.getCanonicalName());

    IOFSwitch sw = switchService.getSwitch(switchId);
    Future<OFFeaturesReply> future;
    OFFeaturesReply featuresReply = null;
    OFFeaturesRequest featuresRequest = sw.getOFFactory().buildFeaturesRequest().build();
    if (sw != null) {
        try {
            future = sw.writeRequest(featuresRequest);
            featuresReply = future.get(10, TimeUnit.SECONDS);
        } catch (Exception e) {
            log.error("Failure getting features reply from switch" + sw, e);
        }
    }

    return featuresReply;
}
项目:neoscada    文件:Activator.java   
@Override
public void start ( final BundleContext bundleContext ) throws Exception
{
    this.executor = new ExportedExecutorService ( "org.eclipse.scada.ca.server.osgi", 1, 1, 1, TimeUnit.MINUTES );

    Activator.context = bundleContext;
    this.tracker = new SingleServiceTracker<ConfigurationAdministrator> ( bundleContext, ConfigurationAdministrator.class, new SingleServiceListener<ConfigurationAdministrator> () {

        @Override
        public void serviceChange ( final ServiceReference<ConfigurationAdministrator> reference, final ConfigurationAdministrator service )
        {
            setService ( service );
        }
    } );
    this.tracker.open ();
}
项目:rocketmq-rocketmq-all-4.1.0-incubating    文件:ConsumeMessageOrderlyService.java   
private void submitConsumeRequestLater(//
    final ProcessQueue processQueue, //
    final MessageQueue messageQueue, //
    final long suspendTimeMillis//
) {
    long timeMillis = suspendTimeMillis;
    if (timeMillis == -1) {
        timeMillis = this.defaultMQPushConsumer.getSuspendCurrentQueueTimeMillis();
    }

    if (timeMillis < 10) {
        timeMillis = 10;
    } else if (timeMillis > 30000) {
        timeMillis = 30000;
    }

    this.scheduledExecutorService.schedule(new Runnable() {

        @Override
        public void run() {
            ConsumeMessageOrderlyService.this.submitConsumeRequest(null, processQueue, messageQueue, true);
        }
    }, timeMillis, TimeUnit.MILLISECONDS);
}
项目:weex-3d-map    文件:WXWebSocketManager.java   
public void connect(String url) {
  try {
    mHttpClient= (OkHttpClient) Class.forName("com.squareup.okhttp.OkHttpClient").newInstance();
  } catch (Exception e) {
    isSupportWebSocket =false;
    return;
  }
  mHttpClient.setConnectTimeout(10, TimeUnit.SECONDS);
  mHttpClient.setWriteTimeout(10, TimeUnit.SECONDS);
  // Disable timeouts for read
  mHttpClient.setReadTimeout(0, TimeUnit.MINUTES);

  Request request = new Request.Builder().url(url).build();
  WebSocketCall call = WebSocketCall.create(mHttpClient, request);
  call.enqueue(this);
}
项目:RxJavaEspressoSample    文件:RxJava1Activity.java   
@Override
protected void onStart() {
    super.onStart();
    compositeSubscription.add(RxView.clicks(binding.buttonDebounce)
            .observeOn(Schedulers.computation())
            .debounce(3, TimeUnit.SECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(v -> binding.textDebounceResult.setText("Debounce Completed")));

    compositeSubscription.add(RxView.clicks(binding.buttonSleep)
            .observeOn(Schedulers.io())
            .map(v -> {
                SystemClock.sleep(3000L);
                return v;
            })
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(v -> binding.textSleepResult.setText("Sleep Completed")));
}
项目:Go-RxJava    文件:RxBinding_Rxlifecycle.java   
@Override
public void runCode() {
    super.runCode();
    Observable.interval(2, TimeUnit.SECONDS)
            .compose(this.bindToLifecycle())
            .subscribe(new Action1<Object>() {
                @Override
                public void call(Object num) {
                    println(count++);
                }
            });
    Observable.interval(2, TimeUnit.SECONDS)
            .compose(this.bindUntilEvent(PAUSE))
            .subscribe(new Action1<Object>() {
                @Override
                public void call(Object o) {
                    println(System.currentTimeMillis());
                }
            });
}
项目:MADBike    文件:PlaceAutocompleteAdapter.java   
private ArrayList<AutocompletePrediction> getAutocomplete(CharSequence constraint) {
    if (mGoogleApiClient.isConnected()) {

        PendingResult<AutocompletePredictionBuffer> results =
                Places.GeoDataApi
                        .getAutocompletePredictions(mGoogleApiClient, constraint.toString(),
                                mBounds, mPlaceFilter);

        AutocompletePredictionBuffer autocompletePredictions = results
                .await(60, TimeUnit.SECONDS);

        final Status status = autocompletePredictions.getStatus();
        if (!status.isSuccess()) {
            Toast.makeText(getContext(), "Error contacting API: " + status.toString(),
                    Toast.LENGTH_SHORT).show();
            autocompletePredictions.release();
            return null;
        }
        return DataBufferUtils.freezeAndClose(autocompletePredictions);
    }
    return null;
}
项目:elastic-db-tools-for-java    文件:PointMapping.java   
/**
 * Performs validation that the local representation is as up-to-date as the representation on the backing data store.
 *
 * @param shardMap
 *            Shard map to which the shard provider belongs.
 * @param conn
 *            Connection used for validation.
 */
@Override
public void validate(StoreShardMap shardMap,
        Connection conn) {
    try {
        log.info("PointMapping Validate Start; Connection: {}", conn.getMetaData().getURL());
        Stopwatch stopwatch = Stopwatch.createStarted();

        ValidationUtils.validateMapping(conn, this.getShardMapManager(), shardMap, this.getStoreMapping());

        stopwatch.stop();

        log.info("PointMapping Validate Complete; Connection: {}; Duration:{}", conn.getMetaData().getURL(),
                stopwatch.elapsed(TimeUnit.MILLISECONDS));
    }
    catch (SQLException e) {
        e.printStackTrace();
        throw (ShardManagementException) e.getCause();
    }
}
项目:openrouteservice-tools    文件:OSMInputFile.java   
private Entity getNextPBF()
{
    Entity next = null;
    while (next == null)
    {
        if (!hasIncomingData && _entityQueue.isEmpty())
        {
            // we are done, stop polling
            eof = true;
            break;
        }

        try
        {
            // we cannot use "itemQueue.take()" as it blocks and hasIncomingData can change
            next = _entityQueue.poll(10, TimeUnit.MILLISECONDS);
        } catch (InterruptedException ex)
        {
            eof = true;
            break;
        }
    }

    return next;
}
项目:fresco_floodlight    文件:TopologyManager.java   
@Override
public void run() {
    try {
        if (ldUpdates.peek() != null) {
            updateTopology();
        }
        handleMiscellaneousPeriodicEvents();
    }
    catch (Exception e) {
        log.error("Error in topology instance task thread", e);
    } finally {
        if (floodlightProviderService.getRole() != HARole.STANDBY) {
            newInstanceTask.reschedule(TOPOLOGY_COMPUTE_INTERVAL_MS, TimeUnit.MILLISECONDS);
        }
    }
}
项目:incubator-servicecomb-java-chassis    文件:MicroserviceVersions.java   
@Subscribe
public void onMicroserviceInstanceChanged(MicroserviceInstanceChangedEvent changedEvent) {
  if (!appId.equals(changedEvent.getKey().getAppId()) ||
      !microserviceName.equals(changedEvent.getKey().getServiceName())) {
    return;
  }

  // pull instances always replace old instances, not append
  //
  // pull result and watch event sequence is not defined even inside SC.
  // it's not safe to trust the event, so we just send a new pull request
  //
  // CREATE/UPDATE:
  //   if pull 1/2/3, and then add 4, but "add 4" received before pull result, will lost 4.
  // DELETE:
  //   if pull 1/2/3, and then delete 3, but "delete 3" received before pull result, will have wrong 3.
  // EXPIRE::
  //   black/white config in SC changed, we must refresh all data from sc.
  pendingPullCount.incrementAndGet();
  appManager.getEventBus().post(new PullMicroserviceVersionsInstancesEvent(this, TimeUnit.SECONDS.toMillis(1)));
}
项目:illuminati    文件:IlluminatiTemplateExecutorImpl.java   
@Override public IlluminatiTemplateInterfaceModel deQueueByDebug () {
    ILLUMINATI_TEMPLATE_EXECUTOR_LOGGER.info("template queue current size is "+String.valueOf(this.getQueueSize()));

    if (ILLUMINATI_MODEL_BLOCKING_QUEUE == null || this.getQueueSize() == 0) {
        return null;
    }
    try {
        final long start = System.currentTimeMillis();
        IlluminatiTemplateInterfaceModel illuminatiTemplateInterfaceModel = ILLUMINATI_MODEL_BLOCKING_QUEUE.poll(ILLUMINATI_DEQUEUING_TIMEOUT_MS, TimeUnit.MILLISECONDS);
        final long elapsedTime = System.currentTimeMillis() - start;
        ILLUMINATI_TEMPLATE_EXECUTOR_LOGGER.info("template queue after inserted size is "+String.valueOf(this.getQueueSize()));
        ILLUMINATI_TEMPLATE_EXECUTOR_LOGGER.info("elapsed time of dequeueing template queue is "+elapsedTime+" millisecond");
        return illuminatiTemplateInterfaceModel;
    } catch (InterruptedException e) {
        ILLUMINATI_TEMPLATE_EXECUTOR_LOGGER.warn("Failed to dequeing the rabbitmq queue.. ("+e.getMessage()+")");
    }

    return null;
}
项目:starcor.xul    文件:XulHttpServer.java   
private void _initServer(String addr, int port) {
    _localAddr = addr;
    _localPort = port;
    _workerGroup = new ThreadGroup("Xul HTTP Server");
    ThreadFactory threadFactory = new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
            return new Thread(_workerGroup, r, "Reactor");
        }
    };
    _reactorPool = new ThreadPoolExecutor(1, 16, 10, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(16), threadFactory);

    _listeningWorker = new Thread(_workerGroup, "Acceptor") {
        @Override
        public void run() {
            _doWork();
        }
    };
    _listeningWorker.start();
}
项目:reading-and-annotate-rocketmq-3.4.6    文件:FiltersrvController.java   
public boolean initialize() {
    MixAll.printObjectProperties(log, this.filtersrvConfig);

    this.remotingServer = new NettyRemotingServer(this.nettyServerConfig);

    this.remotingExecutor =
            Executors.newFixedThreadPool(nettyServerConfig.getServerWorkerThreads(),
                new ThreadFactoryImpl("RemotingExecutorThread_"));

    this.registerProcessor();

    this.scheduledExecutorService.scheduleAtFixedRate(new Runnable() {

        @Override
        public void run() {
            FiltersrvController.this.registerFilterServerToBroker();
        }
    }, 3, 10, TimeUnit.SECONDS);

    this.defaultMQPullConsumer.setBrokerSuspendMaxTimeMillis(this.defaultMQPullConsumer
        .getBrokerSuspendMaxTimeMillis() - 1000);
    this.defaultMQPullConsumer.setConsumerTimeoutMillisWhenSuspend(this.defaultMQPullConsumer
        .getConsumerTimeoutMillisWhenSuspend() - 1000);

    this.defaultMQPullConsumer.setNamesrvAddr(this.filtersrvConfig.getNamesrvAddr());
    this.defaultMQPullConsumer.setInstanceName(String.valueOf(UtilAll.getPid()));

    return true;
}
项目:NBANDROID-V2    文件:AndroidSdkImpl.java   
@Override
public void setSdkRootFolder(String sdkPath) {
    String last = this.sdkPath;
    this.sdkPath = sdkPath;
    sdkRoot = new File(sdkPath);
    sdkRootFo = FileUtil.toFileObject(sdkRoot);
    firePropertyChange(LOCATION, last, sdkPath);
    platforms.clear();
    platformsList.clear();
    final Runnable runnable = new Runnable() {

        @Override
        public void run() {
            androidSdkHandler = AndroidSdkHandler.getInstance(sdkRoot);
            if (androidSdkHandler != null) {
                repoManager = androidSdkHandler.getSdkManager(new NbOutputWindowProgressIndicator());
                repoManager.registerLocalChangeListener(AndroidSdkImpl.this);
                repoManager.registerRemoteChangeListener(AndroidSdkImpl.this);
                androidTargetManager = androidSdkHandler.getAndroidTargetManager(new NbOutputWindowProgressIndicator() {
                });
                updateSdkPlatformPackages();
                scheduledThreadPool.scheduleWithFixedDelay(new Runnable() {
                    @Override
                    public void run() {
                        repoManager.reloadLocalIfNeeded(new NbOutputWindowProgressIndicator());
                    }
                }, 30, 30, TimeUnit.SECONDS);
            } else {
                repoManager = null;
            }
        }
    };
    WindowManager.getDefault().invokeWhenUIReady(new Runnable() {
        @Override
        public void run() {
            AndroidSdk.pool.submit(runnable);
        }
    });
}
项目:JRediClients    文件:JCacheTest.java   
@Test
public void testExpiration() throws InterruptedException, IllegalArgumentException, URISyntaxException, FailedToStartRedisException, IOException {
    RedisProcess runner = new RedisRunner()
            .nosave()
            .randomDir()
            .port(6311)
            .run();

    MutableConfiguration<String, String> config = new MutableConfiguration<>();
    config.setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(new Duration(TimeUnit.SECONDS, 1)));
    config.setStoreByValue(true);

    URI configUri = getClass().getResource("redisson-jcache.json").toURI();
    Cache<String, String> cache = Caching.getCachingProvider().getCacheManager(configUri, null)
            .createCache("test", config);

    CountDownLatch latch = new CountDownLatch(1);

    String key = "123";
    ExpiredListener clientListener = new ExpiredListener(latch, key, "90");
    MutableCacheEntryListenerConfiguration<String, String> listenerConfiguration = 
            new MutableCacheEntryListenerConfiguration<String, String>(FactoryBuilder.factoryOf(clientListener), null, true, true);
    cache.registerCacheEntryListener(listenerConfiguration);

    cache.put(key, "90");
    Assert.assertNotNull(cache.get(key));

    latch.await();

    Assert.assertNull(cache.get(key));

    cache.close();
    runner.stop();
}
项目:JRediClients    文件:RedissonRemoteService.java   
private <T extends RRemoteServiceResponse> RFuture<BatchResult<?>> send(long timeout, String responseName, T response) {
    RBatch batch = redisson.createBatch();
    RBlockingQueueAsync<T> queue = batch.getBlockingQueue(responseName, getCodec());
    queue.putAsync(response);
    queue.expireAsync(timeout, TimeUnit.MILLISECONDS);
    return batch.executeAsync();
}
项目:lemon    文件:HttpFuture.java   
public String readText(ExecutorService executorService, long timeout)
        throws IOException, InterruptedException, ExecutionException,
        TimeoutException {
    FutureTask<String> futureTask = new FutureTask(this);
    executorService.execute(futureTask);

    String text = futureTask.get(timeout, TimeUnit.MILLISECONDS);

    return text;
}
项目:hashsdn-controller    文件:RpcRegistryTest.java   
/**
 * Three node cluster. Register rpc on 2 nodes. Ensure 3rd gets updated.
 */
@Test
public void testRpcAddedOnMultiNodes() throws Exception {
    final JavaTestKit testKit = new JavaTestKit(node3);

    // Add rpc on node 1
    List<DOMRpcIdentifier> addedRouteIds1 = createRouteIds();
    registry1.tell(new AddOrUpdateRoutes(addedRouteIds1), ActorRef.noSender());

    final UpdateRemoteEndpoints req1 = registrar3.expectMsgClass(Duration.create(3, TimeUnit.SECONDS),
        UpdateRemoteEndpoints.class);

    // Add rpc on node 2
    List<DOMRpcIdentifier> addedRouteIds2 = createRouteIds();
    registry2.tell(new AddOrUpdateRoutes(addedRouteIds2), ActorRef.noSender());

    final UpdateRemoteEndpoints req2 = registrar3.expectMsgClass(Duration.create(3, TimeUnit.SECONDS),
        UpdateRemoteEndpoints.class);
    Address node2Address = node2.provider().getDefaultAddress();
    Address node1Address = node1.provider().getDefaultAddress();

    Map<Address, Bucket<RoutingTable>> buckets = retrieveBuckets(registry3, testKit, node1Address,
            node2Address);

    verifyBucket(buckets.get(node1Address), addedRouteIds1);
    verifyBucket(buckets.get(node2Address), addedRouteIds2);

    Map<Address, Long> versions = retrieveVersions(registry3, testKit);
    Assert.assertEquals("Version for bucket " + node1Address, (Long) buckets.get(node1Address).getVersion(),
            versions.get(node1Address));
    Assert.assertEquals("Version for bucket " + node2Address, (Long) buckets.get(node2Address).getVersion(),
            versions.get(node2Address));

    assertEndpoints(req1, node1Address, invoker1);
    assertEndpoints(req2, node2Address, invoker2);

}
项目:AthenaX    文件:InstanceManager.java   
@Override
public void run() {
  try {
    scanAll();
  } catch (Throwable e) {
    LOG.warn("Failed to scan the applications {}", e);
  } finally {
    if (running) {
      executor.schedule(thunk, rescanInterval, TimeUnit.MILLISECONDS);
    }
  }
}
项目:Equella    文件:ResourcesServlet.java   
public ResourcesServlet()
{
    long twentyFiveYearsInMillis = TimeUnit.DAYS.toMillis(365) * 25;

    maxAge = "max-age=" + TimeUnit.MILLISECONDS.toSeconds(twentyFiveYearsInMillis) + ", public";
    expires = System.currentTimeMillis() + twentyFiveYearsInMillis;
}
项目:HuskyCrates-Sponge    文件:InstantGUIView.java   
public InstantGUIView(HuskyCrates plugin, Player runner, VirtualCrate virtualCrate){
    //System.out.println("AA");
    this.plugin = plugin;
    vc = virtualCrate;
    ourplr = runner;
    items = vc.getItemSet();
    if(virtualCrate.scrambleRewards){
        scrambleRewards();
    }
    disp = Inventory.builder()
            .of(InventoryArchetypes.DISPENSER)
            .listener(InteractInventoryEvent.class, evt ->{
                if(!(evt instanceof InteractInventoryEvent.Open) && !(evt instanceof  InteractInventoryEvent.Close)){
                    evt.setCancelled(true);
                }

            })
            .property(InventoryTitle.PROPERTY_NAME,InventoryTitle.of(TextSerializers.FORMATTING_CODE.deserialize(virtualCrate.displayName)))
            .build(plugin);
    updateInv(0);
    Scheduler scheduler = Sponge.getScheduler();
    Task.Builder taskBuilder = scheduler.createTaskBuilder();
    updater = taskBuilder.execute(this::updateTick).intervalTicks(1).submit(plugin);
    scheduler.createTaskBuilder().execute(() -> {
        updater.cancel();
        ourplr.closeInventory();
        handleReward(holder);
        ourplr.playSound(SoundTypes.ENTITY_EXPERIENCE_ORB_PICKUP,ourplr.getLocation().getPosition(),1);
    }).delay(3, TimeUnit.SECONDS).submit(HuskyCrates.instance);
}
项目:jdk8u-jdk    文件:bug6489130.java   
public static void main(String[] args) throws InterruptedException {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            new bug6489130().run();
        }
    });

    if (!MUX.await(10, TimeUnit.SECONDS)) {
        throw new RuntimeException("Timeout");
    }
}
项目:LoRaWAN-Smart-Parking    文件:OkHttpClient.java   
/**
 * Sets the default connect timeout for new connections. A value of 0 means no timeout.
 *
 * @see URLConnection#setConnectTimeout(int)
 */
public void setConnectTimeout(long timeout, TimeUnit unit) {
  if (timeout < 0) {
    throw new IllegalArgumentException("timeout < 0");
  }
  if (unit == null) {
    throw new IllegalArgumentException("unit == null");
  }
  long millis = unit.toMillis(timeout);
  if (millis > Integer.MAX_VALUE) {
    throw new IllegalArgumentException("Timeout too large.");
  }
  connectTimeout = (int) millis;
}
项目:otter-G    文件:MonitorScheduler.java   
/**
 * 注册对应的Monitor对象
 * 
 * @param monitor
 * @param period 调度周期,单位ms
 */
public static void register(final Monitor monitor, Long delay, Long period) {
    ScheduledFuture future = scheduler.scheduleAtFixedRate(new Runnable() {

        public void run() {
            monitor.reload();
        }
    }, delay, period, TimeUnit.MILLISECONDS);

    register.put(monitor, future);
}
项目:GitHub    文件:SimpleMockService.java   
public static void main(String... args) throws IOException {
  // Create a very simple Retrofit adapter which points the GitHub API.
  Retrofit retrofit = new Retrofit.Builder()
      .baseUrl(SimpleService.API_URL)
      .build();

  // Create a MockRetrofit object with a NetworkBehavior which manages the fake behavior of calls.
  NetworkBehavior behavior = NetworkBehavior.create();
  MockRetrofit mockRetrofit = new MockRetrofit.Builder(retrofit)
      .networkBehavior(behavior)
      .build();

  BehaviorDelegate<GitHub> delegate = mockRetrofit.create(GitHub.class);
  MockGitHub gitHub = new MockGitHub(delegate);

  // Query for some contributors for a few repositories.
  printContributors(gitHub, "square", "retrofit");
  printContributors(gitHub, "square", "picasso");

  // Using the mock-only methods, add some additional data.
  System.out.println("Adding more mock data...\n");
  gitHub.addContributor("square", "retrofit", "Foo Bar", 61);
  gitHub.addContributor("square", "picasso", "Kit Kat", 53);

  // Reduce the delay to make the next calls complete faster.
  behavior.setDelay(500, TimeUnit.MILLISECONDS);

  // Query for the contributors again so we can see the mock data that was added.
  printContributors(gitHub, "square", "retrofit");
  printContributors(gitHub, "square", "picasso");
}
项目:GitHub    文件:HandlerSchedulerTest.java   
@Test
public void directScheduleOnceWithNegativeDelayPostsImmediately() {
    CountingRunnable counter = new CountingRunnable();
    scheduler.scheduleDirect(counter, -1, TimeUnit.MINUTES);

    runUiThreadTasks();
    assertEquals(1, counter.get());
}
项目:Channelize    文件:TimerFragment.java   
private void setScreenElements() {
    mCircularProgressBar = (HoloCircularProgressBar) view.findViewById(R.id.circular_progressBar);
    mTextViewTimer = (TextView)view.findViewById(R.id.text_timer);
    mButtonStart = (Button)view.findViewById(R.id.button_start);
    mButtonPause = (Button)view.findViewById(R.id.button_pause);
    mButtonResume = (Button)view.findViewById(R.id.button_resume);
    mButtonStop = (Button)view.findViewById(R.id.button_stop);

    if (mTextViewTimer != null) {
        mTextViewTimer.setTypeface(Typeface.createFromAsset(getActivity().getAssets(), "fonts/Roboto-Light.ttf"));
    }

    updateTimerLabel((int) TimeUnit.MINUTES.toSeconds(timerDuration));
}
项目:letv    文件:LooperScheduler.java   
public Subscription schedule(Action0 action, long delayTime, TimeUnit unit) {
    if (this.unsubscribed) {
        return Subscriptions.unsubscribed();
    }
    Subscription scheduledAction = new ScheduledAction(this.hook.onSchedule(action), this.handler);
    Message message = Message.obtain(this.handler, scheduledAction);
    message.obj = this;
    this.handler.sendMessageDelayed(message, unit.toMillis(delayTime));
    if (!this.unsubscribed) {
        return scheduledAction;
    }
    this.handler.removeCallbacks(scheduledAction);
    return Subscriptions.unsubscribed();
}
项目:L2J-Global    文件:ThreadPoolManager.java   
/**
 * Schedules a general task to be executed at fixed rate.
 * @param task the task to execute
 * @param initialDelay the initial delay in the given time unit
 * @param period the period between executions in the given time unit
 * @param unit the time unit of the initialDelay and period parameters
 * @return a ScheduledFuture representing pending completion of the task, and whose get() method will throw an exception upon cancellation
 */
public ScheduledFuture<?> scheduleGeneralAtFixedRate(Runnable task, long initialDelay, long period, TimeUnit unit)
{
    try
    {
        return _generalScheduledThreadPool.scheduleAtFixedRate(new RunnableWrapper(task), initialDelay, period, unit);
    }
    catch (RejectedExecutionException e)
    {
        return null; /* shutdown, ignore */
    }
}
项目:OpenJSharp    文件:FileTime.java   
private long toDays() {
    if (unit != null) {
        return unit.toDays(value);
    } else {
        return TimeUnit.SECONDS.toDays(toInstant().getEpochSecond());
    }
}
项目:hadoop    文件:FairCallQueue.java   
@Override
public boolean offer(E e, long timeout, TimeUnit unit)
    throws InterruptedException {
  int priorityLevel = scheduler.getPriorityLevel(e);
  BlockingQueue<E> q = this.queues.get(priorityLevel);
  boolean ret = q.offer(e, timeout, unit);

  signalNotEmpty();

  return ret;
}