如何使用定时执行服务每天在特定时间运行特定任务?
我试图每天凌晨5点运行某个任务。所以我决定使用它,但到目前为止,我已经看到了演示如何每隔几分钟运行一次任务的示例。ScheduledExecutorService
而且我无法找到任何示例来显示如何每天在早上的特定时间(凌晨5点)运行任务,并且还考虑了夏令时的事实 -
以下是我的代码,每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();
}
}
有没有办法,我可以安排一个任务每天凌晨5点运行,同时考虑到夏令时的事实?ScheduledExecutorService
而且也比这更好还是?TimerTask
ScheduledExecutorService