如何安排Callable在特定时间运行?

Yos*_*ale 2 java scheduling callable

我需要在一天的特定时间运行一个可调用的.一种方法是计算now和所需时间之间的timediff,并使用executor.scheduleAtFixedRate.

有更好的主意吗?

executor.scheduleAtFixedRate(command, TIMEDIFF(now,run_time), period, TimeUnit.SECONDS))

cle*_*tus 11

对于这种事情,请继续安装Quartz.EJB对这种事情有一些支持,但实际上你只需要Quartz来完成计划任务.

话虽如此,如果你坚持自己做(并且我建议不要),请使用ScheduledThreadPoolExecutor.

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

Runnable每天运行一次,最初延迟一小时.

要么:

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

Timer有一个更简单的接口,并在1.3(另一个是1.5)中引入,但单个线程执行所有任务,而第一个允许您配置.加上ScheduledExecutorService更好的关闭(和其他)方法.