Java定时任务的几种方法(Thread 和 Timer,线程池)

时间:2023-03-10 07:21:47
Java定时任务的几种方法(Thread 和 Timer,线程池)
  1. /**
  2. * 普通thread
  3. * 这是最常见的,创建一个thread,然后让它在while循环里一直运行着,
  4. * 通过sleep方法来达到定时任务的效果。这样可以快速简单的实现,代码如下:
  5. *
  6. */
  7. public class Task1 {
  8. public static void main(String[] args) {
  9. // run in a second
  10. final long timeInterval = 1000;
  11. Runnable runnable = new Runnable() {
  12. public void run() {
  13. while (true) {
  14. // ------- code for task to run
  15. System.out.println("Hello !!");
  16. // ------- ends here
  17. try {
  18. Thread.sleep(timeInterval);
  19. } catch (InterruptedException e) {
  20. e.printStackTrace();
  21. }
  22. }
  23. }
  24. };
  25. Thread thread = new Thread(runnable);
  26. thread.start();
  27. }
  28. }
  1. /**
  2. *
  3. * 于第一种方式相比,优势 1>当启动和去取消任务时可以控制 2>第一次执行任务时可以指定你想要的delay时间
  4. *
  5. * 在实现时,Timer类可以调度任务,TimerTask则是通过在run()方法里实现具体任务。 Timer实例可以调度多任务,它是线程安全的。
  6. * 当Timer的构造器被调用时,它创建了一个线程,这个线程可以用来调度任务。 下面是代码:
  7. *
  8. */
  1. import java.util.Timer;
  2. import java.util.TimerTask;
  3. public class Task2 {
  4. public static void main(String[] args) {
  5. TimerTask task = new TimerTask() {
  6. @Override
  7. public void run() {
  8. // task to run goes here
  9. System.out.println("Hello !!!");
  10. }
  11. };
  12. Timer timer = new Timer();
  13. long delay = 0;
  14. long intevalPeriod = 1 * 1000;
  15. // schedules the task to be run in an interval
  16. timer.scheduleAtFixedRate(task, delay, intevalPeriod);
  17. timer.schedule(task, delay);
  18. } // end of main
  19. }
  1. /**
  2. * ScheduledExecutorService是从Java SE5的java.util.concurrent里,做为并发工具类被引进的,这是最理想的定时任务实现方式。
  3. * 相比于上两个方法,它有以下好处:
  4. * 1>相比于Timer的单线程,它是通过线程池的方式来执行任务的
  5. * 2>可以很灵活的去设定第一次执行任务delay时间
  6. * 3>提供了良好的约定,以便设定执行的时间间隔
  7. *
  8. * 下面是实现代码,我们通过ScheduledExecutorService#scheduleAtFixedRate展示这个例子,通过代码里参数的控制,首次执行加了delay时间。
  9. *
  10. */
    1. import java.util.concurrent.Executors;
    2. import java.util.concurrent.ScheduledExecutorService;
    3. import java.util.concurrent.TimeUnit;
    4. public class Task3 {
    5. public static void main(String[] args) {
    6. Runnable runnable = new Runnable() {
    7. public void run() {
    8. // task to run goes here
    9. System.out.println("Hello !!");
    10. }
    11. };
    12. ScheduledExecutorService service = Executors
    13. .newSingleThreadScheduledExecutor();
    14. // 第二个参数为首次执行的延时时间,第三个参数为定时执行的间隔时间
    15. service.scheduleAtFixedRate(runnable, 10, 1, TimeUnit.SECONDS);
    16. //        创建并执行在给定延迟后启用的 ScheduledFuture。
      //        参数:
      //        callable - 要执行的功能
      //        delay - 从现在开始延迟执行的时间
      //        unit - 延迟参数的时间单位
      //        返回:
      //        可用于提取结果或取消的 ScheduledFuture
    17. service.schedule(runnable, delay, TimeUnit.MILLISECONDS);
    18. }
    19. }