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

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


当前回答

你应该看看Quartz,它是一个java框架,适用于EE和SE版本,并允许定义作业来执行特定的时间

其他回答

试试这种方式——>

首先创建一个运行任务的类TimeTask,它看起来像:

public class CustomTask extends TimerTask  {

   public CustomTask(){
 
     //Constructor

   }

   public void run() {
       try {
     
         // Your task process

       } catch (Exception ex) {
           System.out.println("error running thread " + ex.getMessage());
       }
    }
}

然后在main类中实例化任务,并定期运行它,从一个精确的日期开始:

 public void runTask() {

        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        calendar.set(Calendar.HOUR_OF_DAY, 15);
        calendar.set(Calendar.MINUTE, 40);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);


    
        Timer time = new Timer(); // Instantiate Timer Object

        // Start running the task on Monday at 15:40:00, period is set to 8 hours
        // if you want to run the task immediately, set the 2nd parameter to 0
        time.schedule(new CustomTask(), calendar.getTime(), TimeUnit.HOURS.toMillis(8));
}

如果你想继续使用java.util。计时器,你可以用它来安排大的时间间隔。你只需在你所追求的时间段内通过即可。在这里查看文档。

你应该看看Quartz,它是一个java框架,适用于EE和SE版本,并允许定义作业来执行特定的时间

这两个类可以一起工作来安排一个周期性任务:

计划任务

import java.util.TimerTask;
import java.util.Date;

// Create a class extending TimerTask
public class ScheduledTask extends TimerTask {
    Date now; 
    public void run() {
        // Write code here that you want to execute periodically.
        now = new Date();                      // initialize date
        System.out.println("Time is :" + now); // Display current time
    }
}

运行定时任务

import java.util.Timer;

public class SchedulerMain {
    public static void main(String args[]) throws InterruptedException {
        Timer time = new Timer();               // Instantiate Timer Object
        ScheduledTask st = new ScheduledTask(); // Instantiate SheduledTask class
        time.schedule(st, 0, 1000);             // Create task repeating every 1 sec
        //for demo only.
        for (int i = 0; i <= 5; i++) {
            System.out.println("Execution in Main Thread...." + i);
            Thread.sleep(2000);
            if (i == 5) {
                System.out.println("Application Terminates");
                System.exit(0);
            }
        }
    }
}

参考https://www.mkyong.com/java/how-to-run-a-task-periodically-in-java/

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

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