我需要在一天中的特定时间运行可调用的。一种方法是计算现在与所需时间之间的时间差,并使用 executor.scheduleAtFixedRate。
有更好的主意吗?
executor.scheduleAtFixedRate(command, TIMEDIFF(now,run_time), period, TimeUnit.SECONDS))
对于这种事情,直接安装即可Quartz http://www.quartz-scheduler.org/。 EJB 对此类事情有一些支持,但实际上您只需要 Quartz 来执行计划任务。
话虽这么说,如果您坚持自己做(我建议不要这样做),请使用ScheduledThreadPoolExecutor http://java.sun.com/javase/6/docs/api/java/util/concurrent/ScheduledThreadPoolExecutor.html.
ScheduledExecutorService executor = new ScheduledThreadPoolExecutor(4);
ScheduledFuture<?> future =
executor.scheduleAtFixedRate(runnable, 1, 24, TimeUnit.HOUR);
这将运行Runnable
每天,最初延迟一小时。
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
有一个更简单的界面,在 1.3 中引入(另一个是 1.5),但单个线程执行所有任务,而第一个线程允许您对其进行配置。加ScheduledExecutorService
有更好的关闭(和其他)方法。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)