How to schedule a Callable to run on a specific time?

callable, java, scheduling

Solution

For this kind of thing, just go ahead and install Quartz. EJB has some support for this kind of thing but really you just want Quartz for scheduled tasks.

That being said, if you insist on doing it yourself (and I'd recommend not), use the `ScheduledThreadPoolExecutor`.

ScheduledExecutorService executor = new ScheduledThreadPoolExecutor(4);
ScheduledFuture<?> future =
  executor.scheduleAtFixedRate(runnable, 1, 24, TimeUnit.HOUR);

which will run the `Runnable` every day with an initial delay of one hour.

Or:

Timer timer = new Timer();
final Callable c = callable;
TimerTask task = new TimerTask() {
  public void run() {
    c.call();
  }
}
t.scheduleAtFixedRate(task, firstExecuteDate, 86400000); // every day

`Timer` has a somewhat simpler interface and was introduced in 1.3 (the other is 1.5) but a single thread executes all tasks whereas the first one allows you to configure that. Plus `ScheduledExecutorService` has nicer shutdown (and other) methods.

Problem

I need to run a callable at a specific time of day. One way to do it is to calculate the timediff between now and the desired time , and to use the executor.scheduleAtFixedRate . Have a better idea? `executor.scheduleAtFixedRate(command, TIMEDIFF(now,run_time), period, TimeUnit.SECONDS))`

Original source