Java实现定时任务的三种方式

来源:互联网 发布:小强软件测试 编辑:程序博客网 时间:2024/04/19 11:49

            无论呈现给用户的是APP还是网页版网站,在应用里都会用到在后台跑定时任务的情况。举个例子,理财产品需要给用户返现,但返现并不是人工触发,这是就需要用到定时任务。在本文,小编将介绍java中三种定时任务的实现方式。

  • 普通thread实现
  • TimerTask实现
  • ScheduledExecutorService实现

普通Thread

            创建一个thread,然后让它在while循环里一直运行着,通过sleep方法来达到定时任务的效果。这样可以快速简单的实现,代码如下:

public class Task {    public static void main(String[] args) {    final long timeInterval = 1000;    Runnable runnable = new Runnable() {      public void run() {        while (true) {          System.out.println("Hello !!");          try {             Thread.sleep(timeInterval);          } catch (InterruptedException e) {            e.printStackTrace();          }        }      }    };    Thread thread = new Thread(runnable);    thread.start();  }}

Timer和TimerTask

            用线程的方式实现非常简便快捷,但是它还缺少一些功能。

用Timer和TimerTask相比thread有以下几点好处:

            可以控制启动和取消任务

            第一次执行任务时可以指定你想要的delay时间

            在实现时,Timer可以调度任务,TimerTask则是通过在run( )方法里实现具体任务。

            Timter可以调度多任务,它是线程安全的。当Timer的构造器被调用时,它创建了一个线程,这个线程可以用来调度任务:

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() {        System.out.println("Hello !!!");      }    };    Timer timer = new Timer();    long delay = 0;    long intevalPeriod = 1 * 1000;    timer.scheduleAtFixedRate(task, delay,intevalPeriod);  } }

ScheduledExecutorService

            ScheduledExecutorService是从Java SE 5java.util.concurrent里,做为并发工具类被引进的,这是最理想的定时任务实现方式。

相比于上两个方法,它有以下好处:

            相比于Timer的单线程,它是通过线程池的方式来执行任务的
            可以很灵活的去设定第一次执行任务delay时间
            提供了良好的约定,以便设定执行的时间间隔


            我们通过ScheduledExecutorService#scheduleAtFixedRate展示这个例子,通过代码里参数的控制,首次执行加了delay时间:

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() {        System.out.println("Hello !!");      }    };    ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();    service.scheduleAtFixedRate(runnable, 0, 1, TimeUnit.SECONDS);  }}


1 0