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

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

我目前正在使用java.util.Timer.scheduleAtFixedRatejava.util.Timer.scheduleAtFixedRate是否支持长时间间隔?


使用ScheduledExecutorService:

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

你应该看看Quartz它是一个Java EE框架,适用于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());
    }
}

然后在主类中实例化任务,并按指定日期定期运行它:

 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));
}
链接地址: http://www.djcxy.com/p/6633.html

上一篇: How to schedule a periodic task in Java?

下一篇: Strategies for handling repetitive background tasks in a Java web application?