BigDataLearner
BigDataLearner

Reputation: 1468

How can I wait for first iteration of a scheduled task to complete?

I scheduled a recurring task. Now I want the main thread to wait for the ScheduledExecutorService to complete its first execution. How can i accomplish this?

public void test1(){
  refreshFunction(); /* This should block until task has executed once. */
  /* Continue with main thread. */
  ... 
}

public void refreshFunction() {
  try {
    scheduledExecutorService = Executors.newScheduledThreadPool(1);
    scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
      @Override
      public void run() {
        loadInfo();
      }
    }, 1, 5, TimeUnit.MINUTES);
    logger.info(" : Completed refreshing information : "
      + new Timestamp(System.currentTimeMillis()));
  } catch (Exception ex) {
    ex.printStackTrace();
  }
}

Upvotes: 0

Views: 2618

Answers (1)

erickson
erickson

Reputation: 269627

Use a CountDownLatch to coordinate between threads.

final CountDownLatch latch = new CountDownLatch(1);
scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
  @Override
  public void run() {
    loadInfo();
    latch.countDown();
  }
}, 1, 5, TimeUnit.MINUTES);
latch.await();

A better approach might be for the scheduled task to execute a callback after the information is loaded to update observers that depend on that information.

Upvotes: 3

Related Questions