[Java]如何安排任务间隔运行

应用程序中经常需要在后台运行某些特定任务以在一定间隔内完成某些工作。 该示例可以是,服务在后台运行以清理应用程序,就像我们有Java Garbage集合一样。

在本文中,我将向您展示3种不同的方法来实现这一目标

他们如下

  • 使用简单的线程
  • 使用TimerTask
  • 使用ScheduledExecutorService

使用简单的线程

这非常简单,它创建了一个简单的线程,使用while循环使其永远运行,并利用sleep方法放置两次运行之间的间隔。

这是实现它的快捷方法

以下是此代码。

public class Task1 {

public static void main(String[] args) {
  // run in a second
  final long timeInterval = 1000;
  Runnable runnable = new Runnable() {
  
  public void run() {
    while (true) {
      // ------- code for task to run
      System.out.println("Hello !!");
      // ------- ends here
      try {
       Thread.sleep(timeInterval);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      }
    }
  };
  
  Thread thread = new Thread(runnable);
  thread.start();
  }
}

使用Timer和TimerTask

我们看到的先前方法是最快的方法,但是缺少一些功能

与以前相比,这具有更多的好处,如下所示

  • 控制何时启动和取消任务
  • 如果需要,可以延迟首次执行,这很有用

在这种情况下,我们使用Timer类进行调度,并使用TimerTask封装要在其run()方法中执行的任务。

计时器实例可以共享以计划多个任务,并且它是线程安全的。

调用Timer构造函数时,它将创建一个线程,并且该单个线程可用于任何任务调度。

出于我们的目的,我们使用Timer#scheduleAtFixedRate

以下代码显示了Timer和TimerTask的用法

import java.util.Timer;
import java.util.TimerTask;

public class Task2 {

  public static void main(String[] args) {
    TimerTask task = new TimerTask() {
      @Override
      public void run() {
        // task to run goes here
        System.out.println("Hello !!!");
      }
    };
    
    Timer timer = new Timer();
    long delay = 0;
    long intevalPeriod = 1 * 1000; 
    
    // schedules the task to be run in an interval 
    timer.scheduleAtFixedRate(task, delay,
                                intevalPeriod);
  
  } // end of main
}

这些类是JDK 1.3中存在的类。

使用ScheduledExecutorService

这是Java SE 5中的java.util.concurrent作为并发实用程序引入的。 这是实现目标的首选方式。

与以前的解决方案相比,它具有以下优点

  • 与TImer的单线程相比,线程池用于执行
  • 提供延迟第一次执行的灵活性
  • 提供良好的约定以提供时间间隔

以下代码显示了相同的用法,

在这里,我们使用ScheduledExecutorService#scheduleAtFixedRate ,如图所示,它将param作为可运行的,我们要运行哪段代码,首次执行的初始延迟

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class Task3 {

  public static void main(String[] args) {
    
    Runnable runnable = new Runnable() {
      public void run() {
        // task to run goes here
        System.out.println("Hello !!");
      }
    };
    
    ScheduledExecutorService service = Executors
                    .newSingleThreadScheduledExecutor();
    service.scheduleAtFixedRate(runnable, 0, 1, TimeUnit.SECONDS);
  }
}

翻译自: https://www.javacodegeeks.com/2014/04/java-how-to-schedule-a-task-to-run-in-an-interval.html