我每天早上 5 点尝试执行某项任务。所以我决定使用ScheduledExecutorService
它,但到目前为止,我已经看到了一些示例,这些示例展示了如何每隔几分钟运行一次任务。
而且我找不到任何示例来说明如何在每天早上的特定时间(5 AM)运行任务,并且还考虑到夏令时的事实 -
下面是我的代码,它将每 15 分钟运行一次 -
public class ScheduledTaskExample {
private final ScheduledExecutorService scheduler = Executors
.newScheduledThreadPool(1);
public void startScheduleTask() {
/**
* not using the taskHandle returned here, but it can be used to cancel
* the task, or check if it's done (for recurring tasks, that's not
* going to be very useful)
*/
final ScheduledFuture<?> taskHandle = scheduler.scheduleAtFixedRate(
new Runnable() {
public void run() {
try {
getDataFromDatabase();
}catch(Exception ex) {
ex.printStackTrace(); //or loggger would be better
}
}
}, 0, 15, TimeUnit.MINUTES);
}
private void getDataFromDatabase() {
System.out.println("getting data...");
}
public static void main(String[] args) {
ScheduledTaskExample ste = new ScheduledTaskExample();
ste.startScheduleTask();
}
}
ScheduledExecutorService
有什么办法,考虑到夏令时的事实,我可以安排一个任务在每天早上 5 点运行吗?
并且TimerTask
对此或更好ScheduledExecutorService
?