如何在Java中安排定期任务?

225

我需要安排一个任务以固定的时间间隔运行。如何在支持长时间间隔的情况下执行此操作(例如每8小时一次)?

我目前正在使用java.util.Timer.scheduleAtFixedRate。这个方法是否支持长时间间隔?

13个回答

3

你尝试过使用注解的 Spring Scheduler 吗?

@Scheduled(cron = "0 0 0/8 ? * * *")
public void scheduledMethodNoReturnValue(){
    //body can be another method call which returns some value.
}

你也可以使用XML来完成这个操作。
 <task:scheduled-tasks>
   <task:scheduled ref = "reference" method = "methodName" cron = "<cron expression here> -or- ${<cron expression from property files>}"
 <task:scheduled-tasks>

0
我的servlet包含了这段代码,如果用户点击接受,如何将其保留在调度程序中。
if(bt.equals("accept")) {
    ScheduledExecutorService scheduler=Executors.newScheduledThreadPool(1);
    String lat=request.getParameter("latlocation");
    String lng=request.getParameter("lnglocation");
    requestingclass.updatelocation(lat,lng);
}

-1

在java.util.concurrent中有一个名为ScheduledFuture的类,它可能会对你有所帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接