Example usage for java.util.concurrent TimeUnit MILLISECONDS

List of usage examples for java.util.concurrent TimeUnit MILLISECONDS

Introduction

In this page you can find the example usage for java.util.concurrent TimeUnit MILLISECONDS.

Prototype

TimeUnit MILLISECONDS

To view the source code for java.util.concurrent TimeUnit MILLISECONDS.

Click Source Link

Document

Time unit representing one thousandth of a second.

Usage

From source file:interactivespaces.liveactivity.runtime.SimpleLiveActivityRunnerSampler.java

@Override
public void startup() {
    liveActivityRunnerSamplerControl = spaceEnvironment.getExecutorService()
            .scheduleAtFixedRate(new Runnable() {
                @Override/*w  ww. jav  a 2  s.  co m*/
                public void run() {
                    sample();
                }
            }, liveActivityRunnerSamplerDelay, liveActivityRunnerSamplerDelay, TimeUnit.MILLISECONDS);
}

From source file:cn.wanghaomiao.seimi.core.SeimiContext.java

protected void waitToEnd() {
    workersPool.shutdown();//ww w .j a v a2 s .  c o  m
    try {
        workersPool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) {
        logger.error(e.getMessage(), e);
    }
}

From source file:com.example.common.LibratoMetricWriter.java

@Override
public void flush() throws IOException {
    try {//w  ww.j av a  2  s.c o m
        BatchResult result = batch.post(librato.getSource(), System.currentTimeMillis() / 1000);
        if (!result.success()) {
            log.warn("Could not post {} (out of {}) batches to librato", result.getFailedPosts().size(),
                    result.getPosts().size());
            if (!result.getFailedPosts().isEmpty()) {
                log.debug("Failed batch: {}", result.getFailedPosts().get(0));
            }
        }
        if (!result.getPosts().isEmpty()) {
            this.batch = new LibratoBatch(librato.getBatchSize(), Sanitizer.NO_OP, librato.getTimeoutMillis(),
                    TimeUnit.MILLISECONDS, librato.getAgent(), poster);
        }
    } catch (

    Exception e)

    {
        log.warn("Cannot post to Librato");
    }
}

From source file:com.datatorrent.demos.dimensions.ads.AdsDimensionStoreOperatorTest.java

@Test
public void testQuery() throws Exception {
    File file = new File(testInfo.getDir());
    FileUtils.deleteDirectory(file);/*from  www. j  a v a  2 s. c  o m*/

    AdsDimensionStoreOperator hdsOut = new AdsDimensionStoreOperator() {
        @Override
        public void setup(OperatorContext arg0) {
            super.setup(arg0);
            super.writeExecutor = super.queryExecutor = MoreExecutors.sameThreadExecutor(); // synchronous processing
        }
    };
    TFileImpl hdsFile = new TFileImpl.DefaultTFileImpl();
    hdsOut.setFileStore(hdsFile);
    hdsFile.setBasePath(testInfo.getDir());
    hdsOut.setAggregator(new AdInfo.AdInfoAggregator());
    hdsOut.setMaxCacheSize(1);
    hdsOut.setFlushIntervalCount(0);
    hdsOut.setup(null);

    hdsOut.setDebug(false);

    CollectorTestSink<AdsDimensionStoreOperator.TimeSeriesQueryResult> queryResults = new CollectorTestSink<AdsDimensionStoreOperator.TimeSeriesQueryResult>();
    @SuppressWarnings({ "unchecked", "rawtypes" })
    CollectorTestSink<Object> tmp = (CollectorTestSink) queryResults;
    hdsOut.queryResult.setSink(tmp);

    hdsOut.beginWindow(1);

    long baseTime = System.currentTimeMillis();
    long baseMinute = TimeUnit.MILLISECONDS.convert(TimeUnit.MINUTES.convert(baseTime, TimeUnit.MILLISECONDS),
            TimeUnit.MINUTES);

    // Check aggregation for ae1 and ae2 as they have same key.
    AdInfo.AdInfoAggregateEvent ae1 = new AdInfo.AdInfoAggregateEvent();
    ae1.publisherId = 1;
    ae1.advertiserId = 2;
    ae1.adUnit = 3;
    ae1.timestamp = baseMinute;
    ae1.clicks = 10;
    hdsOut.input.process(ae1);

    AdInfo.AdInfoAggregateEvent ae2 = new AdInfo.AdInfoAggregateEvent();
    ae2.publisherId = 1;
    ae2.advertiserId = 2;
    ae2.adUnit = 3;
    ae2.timestamp = baseMinute;
    ae2.clicks = 20;
    hdsOut.input.process(ae2);

    AdInfo.AdInfoAggregateEvent ae3 = new AdInfo.AdInfoAggregateEvent();
    ae3.publisherId = 1;
    ae3.advertiserId = 2;
    ae3.adUnit = 3;
    ae3.timestamp = baseMinute + TimeUnit.MILLISECONDS.convert(1, TimeUnit.MINUTES);
    ae3.clicks = 40;
    hdsOut.input.process(ae3);

    hdsOut.endWindow();

    hdsOut.beginWindow(2);

    JSONObject keys = new JSONObject();
    keys.put("publisherId", String.valueOf(1));
    keys.put("advertiserId", String.valueOf(2));
    keys.put("adUnit", String.valueOf(3));

    JSONObject query = new JSONObject();
    query.put("numResults", "20");
    query.put("keys", keys);
    query.put("id", "query1");
    query.put("startTime", baseMinute);
    query.put("endTime", baseMinute + TimeUnit.MILLISECONDS.convert(20, TimeUnit.MINUTES));

    hdsOut.query.process(query.toString());

    Assert.assertEquals("timeSeriesQueries " + hdsOut.timeSeriesQueries, 1, hdsOut.timeSeriesQueries.size());
    AdsDimensionStoreOperator.TimeSeriesQuery aq = hdsOut.timeSeriesQueries.values().iterator().next();
    Assert.assertEquals("numTimeUnits " + hdsOut.timeSeriesQueries, baseMinute, aq.startTime);

    hdsOut.endWindow();

    Assert.assertEquals("queryResults " + queryResults.collectedTuples, 1, queryResults.collectedTuples.size());
    TimeSeriesQueryResult r = queryResults.collectedTuples.iterator().next();
    Assert.assertEquals("result points " + r, 2, r.data.size());

    // ae1 object is stored as referenced in cache, and when new tuple is aggregated,
    // the new values are updated in ae1 itself, causing following check to fail.
    //Assert.assertEquals("clicks", ae1.clicks + ae2.clicks, r.data.get(0).clicks);
    Assert.assertEquals("clicks", 10 + ae2.clicks, r.data.get(0).clicks);
    Assert.assertEquals("clicks", ae3.clicks, r.data.get(1).clicks);

    Assert.assertNotSame("deserialized", ae1, r.data.get(1));
    Assert.assertSame("from cache", ae3, r.data.get(1));

}

From source file:com.toedter.chatty.server.boot.message.web.ChatMessageRepositoryListener.java

private void notifySubscribers(ChatMessage chatMessage) {
    shouldBroadcast.set(true);//from w  ww.j  a  v  a2s  . c o m
    if (!isBroadcasterInitialized.getAndSet(true)) {
        logger.info("Broadcasting initialized");
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
        Runnable broadcasterRunnable = new Runnable() {
            public void run() {
                // logger.info("Broadcasting REFRESH: " + shouldBroadcast.get());
                if (shouldBroadcast.getAndSet(false)) {
                    if (broadcaster == null) {
                        ServletContext servletContext = ServletContextFactory.getDefault().getServletContext();
                        BroadcasterFactory factory = (BroadcasterFactory) servletContext
                                .getAttribute("org.atmosphere.cpr.BroadcasterFactory");
                        broadcaster = factory.lookup("/chatty/atmos/messages");
                    }
                    broadcaster.broadcast("{\"command\":\"reloadChatMessages\"}");
                }
            }
        };
        scheduledExecutorService.scheduleAtFixedRate(broadcasterRunnable, 0, 300, TimeUnit.MILLISECONDS);
    }
}

From source file:org.usergrid.rest.filters.MeteringFilter.java

public MeteringFilter() {
    logger.info("MeteringFilter installed");
    this.activeRequests = Metrics.newCounter(MeteringFilter.class, "activeRequests");
    this.requestTimer = Metrics.newTimer(MeteringFilter.class, "requests", TimeUnit.MILLISECONDS,
            TimeUnit.SECONDS);// w  w  w . j  a  va  2  s . c o  m
}

From source file:io.appium.java_client.service.local.AppiumDriverLocalService.java

@Override
public boolean isRunning() {
    lock.lock();//  w w w  . java 2 s  .  co  m
    if (process == null)
        return false;

    try {
        ping(500, TimeUnit.MILLISECONDS);
        return true;
    } catch (UrlChecker.TimeoutException e) {
        return false;
    } finally {
        lock.unlock();
    }

}

From source file:io.watchcat.node.reporting.ElasticSearchReporter.java

@PostConstruct
public void postConstruct() {
    try {//from w  ww  .jav  a  2s .co m
        registerHostInLinuxGraphIndex();
        setupIndexes();
    } catch (Exception e) {
        e.printStackTrace();
    }
    scheduledExecutorService.scheduleAtFixedRate(this, 5000, 1000, TimeUnit.MILLISECONDS);
}

From source file:com.addthis.hydra.data.util.JSONFetcher.java

public JSONFetcher(int timeout, int retries, int backoffMillis) {
    Preconditions.checkArgument(retries >= 0, "retries argument must be a non-negative integer");
    this.timeout = timeout;
    RetryerBuilder<byte[]> retryerBuilder = RetryerBuilder.<byte[]>newBuilder()
            .retryIfExceptionOfType(IOException.class)
            .withStopStrategy(StopStrategies.stopAfterAttempt(retries + 1));
    if (backoffMillis > 0) {
        retryerBuilder.withWaitStrategy(WaitStrategies.exponentialWait(backoffMillis, TimeUnit.MILLISECONDS));
    } else {//from   www. j  av  a2  s. c o m
        retryerBuilder.withWaitStrategy(WaitStrategies.noWait());
    }
    retryer = retryerBuilder.build();
}

From source file:com.gezhii.fitgroup.network.OkHttpStack.java

@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError {

    OkHttpClient client = mClient.clone();
    //int timeoutMs = request.getTimeoutMs();
    int timeoutMs = 30000;
    Log.i("timeoutMs", timeoutMs);
    client.setConnectTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    client.setReadTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    client.setWriteTimeout(timeoutMs, TimeUnit.MILLISECONDS);

    com.squareup.okhttp.Request.Builder okHttpRequestBuilder = new com.squareup.okhttp.Request.Builder();
    okHttpRequestBuilder.url(request.getUrl());

    Map<String, String> headers = request.getHeaders();
    for (final String name : headers.keySet()) {
        okHttpRequestBuilder.addHeader(name, headers.get(name));
    }//w w w  .  j av  a 2s .  com
    for (final String name : additionalHeaders.keySet()) {
        okHttpRequestBuilder.addHeader(name, additionalHeaders.get(name));
    }

    setConnectionParametersForRequest(okHttpRequestBuilder, request);

    com.squareup.okhttp.Request okHttpRequest = okHttpRequestBuilder.build();
    Call okHttpCall = client.newCall(okHttpRequest);
    Response okHttpResponse = okHttpCall.execute();

    StatusLine responseStatus = new BasicStatusLine(parseProtocol(okHttpResponse.protocol()),
            okHttpResponse.code(), okHttpResponse.message());
    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    response.setEntity(entityFromOkHttpResponse(okHttpResponse));

    Headers responseHeaders = okHttpResponse.headers();
    for (int i = 0, len = responseHeaders.size(); i < len; i++) {
        final String name = responseHeaders.name(i), value = responseHeaders.value(i);
        if (name != null) {
            response.addHeader(new BasicHeader(name, value));
        }
    }

    return response;
}