Example usage for java.util.concurrent TimeUnit SECONDS

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

Introduction

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

Prototype

TimeUnit SECONDS

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

Click Source Link

Document

Time unit representing one second.

Usage

From source file:com.skymobi.monitor.service.TaskService.java

public void scheduledTask(final Project project, final Task task) {
    final String projectName = project.getName();
    //first,cancel old task
    removeScheduled(projectName, task);//  ww  w . ja va2  s. c  o  m
    String taskKey = getTaskKey(projectName, task);
    ScheduledFuture<?> future = executor.schedule(new Runnable() {
        @Override
        public void run() {
            long startTime = System.currentTimeMillis();
            try {
                FutureTask _fuFutureTask = TaskService.this.runScript(task.getScript(), project);
                _fuFutureTask.get(task.getTimeout(), TimeUnit.SECONDS);
            } catch (TimeoutException e) {
                logger.error("execute task timeout,use  {} (second), project={} , script={}",
                        new Object[] { (System.currentTimeMillis() - startTime) / 1000, projectName, task });
            } catch (Exception e) {
                logger.error("execute task ERROR,use  {} (second), project={} , script={}",
                        new Object[] { (System.currentTimeMillis() - startTime) / 1000, projectName, task });
                logger.error("execute task fail", e);
            }
            logger.info("execute task success,use {} (second) , project={} , taskName={}", new Object[] {
                    (System.currentTimeMillis() - startTime) / 1000, projectName, task.getName() });
        }
    }, new CronTrigger(task.getCron()));
    logger.info("add a new task {}", taskKey);
    futures.put(taskKey, future);
}

From source file:com.kazuki43zoo.jpetstore.JpetstoreApplicationTests.java

@Before
public void setupSelenide() {
    browser = HTMLUNIT;//w w  w. ja v  a 2s  .  c  om
    timeout = TimeUnit.SECONDS.toMillis(10);
    baseUrl = String.format("http://localhost:%d", port);
    fastSetValue = true;
}

From source file:com.pinterest.pinlater.backends.mysql.MySQLDataSources.java

public MySQLDataSources(PropertiesConfiguration configuration, String host, int port, String user,
        String passwd, boolean dequeueOnly) {
    int numGeneralConnections = configuration.getInt("BACKEND_CONNECTIONS_PER_SHARD");
    int generalSocketTimeoutMillis = (int) TimeUnit.SECONDS
            .toMillis(configuration.getInt("BACKEND_SOCKET_TIMEOUT_SECONDS"));
    int numMonitorConnections = configuration.getInt("MONITOR_CONNECTIONS_PER_SHARD", 3);
    int monitorSocketTimeoutMillis = (int) TimeUnit.SECONDS
            .toMillis(configuration.getInt("MONITOR_SOCKET_TIMEOUT_SECONDS", 10));
    int maxWaitMillis = configuration.getInt("BACKEND_CONNECTION_MAX_WAIT_MILLIS");
    this.generalDataSource = createDataSource(host, port, user, passwd, numGeneralConnections, maxWaitMillis,
            generalSocketTimeoutMillis);
    this.monitorDataSource = createDataSource(host, port, user, passwd, numMonitorConnections, maxWaitMillis,
            monitorSocketTimeoutMillis);
    this.host = host;
    this.port = port;
    this.user = user;
    this.passwd = passwd;
    this.dequeueOnly = new AtomicBoolean(dequeueOnly);
}

From source file:uk.co.sdev.undertow.rx.services.offers.OffersServiceTest.java

@Test
public void shouldReturnObservableOfOffers() throws Exception {
    OffersService service = new OffersService(mapper, client, "http://localhost:9101/offers");

    stubGet("/offers?count=2", Arrays.asList(new Offer("offer1", "description1", "offer1.jpg"),
            new Offer("offer2", "description2", "offer2.jpg")));

    List<Offer> offers = new ArrayList<>();
    List<Throwable> throwables = new ArrayList<>();

    CountDownLatch finished = new CountDownLatch(1);

    Observable<Offer> offer = service.offers(2);
    new Thread(() -> offer.subscribe(o -> offers.add(o), t -> throwables.add(t), () -> finished.countDown()))
            .start();/* w w  w  .  jav  a 2s .co m*/

    finished.await(5, TimeUnit.SECONDS);

    assertThat(offers.size(), is(2));
    assertThat(offers.get(0).getTitle(), is("offer1"));
    assertThat(offers.get(1).getTitle(), is("offer2"));
}

From source file:com.enitalk.controllers.paypal.BasicPaypal.java

public String authPaypal() {
    String tt = null;//from w ww. j  a va  2s .  co m
    try {
        tt = redis.opsForValue().get("paypal");
        if (StringUtils.isNotBlank(tt)) {
            return tt;
        }

        String url = env.getProperty("paypal.auth");
        String auth = env.getProperty("paypal.client") + ":" + env.getProperty("paypal.secret");
        String encoded = java.util.Base64.getEncoder().encodeToString(auth.getBytes());

        logger.info("Posting paypal auth to {} client {}", url, encoded);
        byte[] json = Request.Post(url).addHeader("Authorization", "Basic " + encoded)
                .bodyForm(Form.form().add("grant_type", "client_credentials").build()).execute().returnContent()
                .asBytes();

        JsonNode tree = jackson.readTree(json);
        tt = tree.path("access_token").asText();
        long duration = tree.path("expires_in").asLong();

        redis.opsForValue().set("paypal", tt, duration - 5, TimeUnit.SECONDS);

    } catch (Exception ex) {
        logger.info("Error auth Paypal {}", ExceptionUtils.getFullStackTrace(ex));
    }
    return tt;
}

From source file:org.balloon_project.overflight.task.importer.Importer.java

public void waitUntilFinished() {
    executorPool.shutdown();/*w  ww. j ava  2 s .c o m*/
    try {
        executorPool.awaitTermination(60, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

From source file:com.netflix.spinnaker.orca.clouddriver.tasks.image.ImageForceCacheRefreshTask.java

@Override
public long getBackoffPeriod() {
    return TimeUnit.SECONDS.toMillis(5);
}

From source file:com.omade.monitor.ClientApplication.java

public static void newVersionCheck() {
    ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
    executor.scheduleAtFixedRate(//  ww  w .j ava  2s . c o  m
            new DoTask(config.getProperty("server.url"), config.getProperty("server.port")), 0, 1,
            TimeUnit.SECONDS);
}

From source file:com.joyent.manta.client.MetricReporterSupplier.java

private static JmxReporter buildJmxReporter(final MantaClientMetricConfiguration metricConfig) {
    return JmxReporter.forRegistry(metricConfig.getRegistry()).convertRatesTo(TimeUnit.SECONDS)
            .convertDurationsTo(TimeUnit.MILLISECONDS).createsObjectNamesWith((type, domain, name) -> {
                final String metricJmxObjectName = String.format(MantaClientAgent.FMT_MBEAN_OBJECT_NAME, name,
                        metricConfig.getClientId());

                try {
                    return new ObjectName(metricJmxObjectName);
                } catch (final MalformedObjectNameException e) {
                    final String msg = String.format(
                            "Unable to create JMX object name for metric: %s (name=%s, clientId=%s)",
                            metricJmxObjectName, name, metricConfig.getClientId());
                    throw new RuntimeException(msg, e);
                }//w w w .j  av a2s  .  c  o m
            }).build();
}

From source file:org.springone2gx_2011.integration.asyncgateway.AsyncGatewayDemo.java

@Test
public void testAsyncGateway() throws Exception {
    ApplicationContext ac = new ClassPathXmlApplicationContext("async-gateway-config.xml",
            AsyncGatewayDemo.class);
    MyGateway gateway = ac.getBean("mathService", MyGateway.class);

    List<Future<String>> results = new ArrayList<Future<String>>();
    for (int i = 0; i < 100; i++) {
        Future<String> result = gateway.process("Hello Spring One");
        results.add(result);/*from   w  w  w .  j a v a  2  s  .  c  om*/
    }

    for (final Future<String> result : results) {
        executor.execute(new Runnable() {
            public void run() {
                try {
                    String finalResult = result.get(timeout, TimeUnit.SECONDS);
                    System.out.println("Final Result is: " + finalResult);
                } catch (ExecutionException e) {
                    System.out.println("Exception happened during the execution of the gateway method: " + e);
                } catch (TimeoutException tex) {
                    System.out.println("Timeout occured while waiting for the execution of the gateway method");
                } catch (Exception ie) {
                    System.out.println(ie);
                    Thread.currentThread().interrupt();
                }
            }
        });
    }
    executor.shutdown();
    executor.awaitTermination(60, TimeUnit.SECONDS);
}