我希望能够在Java中的特定时间安排任务。我知道ExecutorService能够在指定的延迟后定期调度,但我更关注的是一天中的某个时间,而不是某个持续时间之后。
比方说,有没有办法让Runnable在2:00执行,或者我需要计算从现在到2:00的时间,然后调度runnable在该延迟之后执行?
发布于 2011-11-09 22:05:45
你会想要Quartz的。
发布于 2011-11-09 23:36:56
您也可以使用spring注解。
@Scheduled(cron="*/5 * * * * MON-FRI")
public void doSomething() {
// something that should execute on weekdays only
}http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/scheduling.html
发布于 2012-09-07 15:23:57
这就是我用java7SE解决这个问题的方法:
timer = new Timer("Timer", true);
Calendar cr = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
cr.setTimeInMillis(System.currentTimeMillis());
long day = TimeUnit.DAYS.toMillis(1);
//Pay attention - Calendar.HOUR_OF_DAY for 24h day model
//(Calendar.HOUR is 12h model, with p.m. a.m. )
cr.set(Calendar.HOUR_OF_DAY, it.getHours());
cr.set(Calendar.MINUTE, it.getMinutes());
long delay = cr.getTimeInMillis() - System.currentTimeMillis();
//insurance for case then time of task is before time of schedule
long adjustedDelay = (delay > 0 ? delay : day + delay);
timer.scheduleAtFixedRate(new StartReportTimerTask(it), adjustedDelay, day);
//you can use this schedule instead is sure your time is after current time
//timer.scheduleAtFixedRate(new StartReportTimerTask(it), cr.getTime(), day);它碰巧比我想象的要难做得多。
https://stackoverflow.com/questions/8066141
复制相似问题