java实现定时任务的三种方法

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