如何安排Callable在特定时间运行? [英] How to schedule a Callable to run on a specific time?

查看:396
本文介绍了如何安排Callable在特定时间运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 .

有更好的主意吗?

executor.scheduleAtFixedRate(命令,TIMEDIFF(现在) ,run_time),句号,TimeUnit.SECONDS))

推荐答案

对于这种事情,只需继续安装 Quartz 。 EJB对这类事情有一些支持,但实际上你只需要Quartz来完成预定的任务。

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.

如果你坚持自己这样做(我会这样做)建议不要使用 ScheduledThreadPoolExecutor

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);

每天都会运行 Runnable 最初延迟一小时。

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

或者:

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

计时器有点儿更简单的接口并在1.3中引入(另一个是1.5)但单个线程执行所有任务,而第一个允许您配置它。 Plus ScheduledExecutorService 具有更好的关闭(和其他)方法。

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.

这篇关于如何安排Callable在特定时间运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆