Ray*_*Ray 5 java scheduled-tasks executor runnable
我希望能够在Java中的特定时间安排任务.我知道ExecutorService有能力定期安排,并在指定的延迟后安排,但我看的时间比一段时间更长.
有没有办法Runnable在2:00 进行执行,或者我是否需要计算从现在到2:00之间的时间,然后安排runnable在延迟后执行?
你也可以使用spring注释
@Scheduled(cron="*/5 * * * * MON-FRI")
public void doSomething() {
// something that should execute on weekdays only
}
Run Code Online (Sandbox Code Playgroud)
http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/scheduling.html
这就是我使用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);
Run Code Online (Sandbox Code Playgroud)
碰巧比我想的要正确
| 归档时间: |
|
| 查看次数: |
11312 次 |
| 最近记录: |