我需要在固定的时间间隔安排一个任务。在长时间间隔(例如每8小时一次)的支持下,我如何做到这一点?

我目前使用java.util.Timer.scheduleAtFixedRate。java.util.Timer.scheduleAtFixedRate支持长时间间隔吗?


当前回答

您尝试过使用注释的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>

其他回答

使用ScheduledExecutorService:

 private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
 scheduler.scheduleAtFixedRate(yourRunnable, 8, 8, TimeUnit.HOURS);

每一秒都做点什么

Timer timer = new Timer();
timer.schedule(new TimerTask() {
    @Override
    public void run() {
        //code
    }
}, 0, 1000);

您尝试过使用注释的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>

我的servlet包含这作为一个代码如何保持这在调度程序,如果用户按下接受

if(bt.equals("accept")) {
    ScheduledExecutorService scheduler=Executors.newScheduledThreadPool(1);
    String lat=request.getParameter("latlocation");
    String lng=request.getParameter("lnglocation");
    requestingclass.updatelocation(lat,lng);
}

在java.util中有一个ScheduledFuture类。同时,它可能会帮助你。