Timed task execution tool Timer and ScheduledThreadPoolExecutor use

A scheduled task is to execute a program at a specified time, or to execute a scheduled task periodically.

There are many ways to implement timed tasks in Java, mainly some of the methods that come with JDK and open source programs such as Qurtz.

1.Timer 和 TimerTask

Timer just acts as an executor. The real task logic is completed through an abstract class called TimerTask. TimerTask is also a class under the java.util package.
It is an abstract class that implements the Runnable interface and contains an abstract method. The run( ) method requires us to provide specific business implementations ourselves.

The advantage of Timer is its simplicity and ease of use, but since all tasks are scheduled by the same thread,
all tasks are executed serially, and only one task can be executed at the same time, and the delay or exception of the previous task will be will affect subsequent tasks.

Sample code:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

public class TimerTest { 

    //被执行的任务必须继承TimerTask,并且实现run方法

    static class MyTimerTask1 extends TimerTask { 

        public void run() { 

            System.out.println("执行当前线程"+Thread.currentThread().getName()); 

        

    }    

    /**

     * Timer线程不会捕获异常,所以TimerTask抛出的未检查的异常会终止timer线程。

     * 如果Timer线程中存在多个计划任务,其中一个计划任务抛出未检查的异常,则会引起整个Timer线程结束,从而导致其他计划任务无法得到继续执行。  

     * Timer线程时基于绝对时间,因此计划任务对系统的时间的改变是敏感的。

     * Timer是单线程,如果某个任务很耗时,可能会影响其他计划任务的执行。

     * @param args

     * @throws ParseException

     * @throws InterruptedException

     */

    public static void main(String[] args) throws ParseException, InterruptedException { 

        Timer timer = new Timer(); 

        /**

         * scheduleAtFixedRate方式

         * 设定两秒后执行任务

         */

        timer.scheduleAtFixedRate(new MyTimerTask1(), 2000,1000);

        /**

         * schedule添加Date参数

         * 设定任务在执行时间执行

         */

//        SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); 

//        Date time = dateFormatter.parse("2016/03/28 14:40:00"); 

//        timer.schedule(new MyTimerTask1(), time);

        //启动MyTimerTask1线程后,主线程休眠五秒钟,给MyTimerTask1五秒的执行时间

        Thread.sleep(5000);

        //终止Timer线程

        timer.cancel();

        

}

  ScheduledThreadPoolExecutor is recommended after JDK 5.0. A simple understanding of Timer is enough.


2.ScheduledThreadPoolExecutor

ScheduledThreadPoolExecutor belongs to the Executor Framework.
In addition to handling exceptions, it can also execute timed tasks in a multi-threaded manner.
The Timer class executes all TimerTask tasks through a single thread. If the execution of one task is very time-consuming, it will cause problems with the timeliness of other tasks.
The ScheduledThreadPoolExecutor is a multi-threaded execution task based on the thread pool, and there is no such problem.

Learn from an example:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

public class ScheduledThreadPoolExecutorTest {

 

    public static void main(String[] args) { 

        //获得实例,并且设置它的容量为5个 

        ScheduledThreadPoolExecutor sExecutor=new ScheduledThreadPoolExecutor(5);

        MyTask task = new MyTask();

        //隔2秒后开始执行任务,并且在上一次任务开始后隔一秒再执行一次

//      sExecutor.scheduleWithFixedDelay(task, 2, 1, TimeUnit.SECONDS); 

        //隔6秒后执行一次,但只会执行一次

        sExecutor.schedule(task, 6, TimeUnit.SECONDS);

        /**

         * 和Timer类似,也可以直接在任务的run()方法中调用调度方法停止

         * 这个方法会平滑的关闭调度器,等待所有任务结束

         */

        sExecutor.shutdown();

         

    }

     

    static class MyTask implements Runnable{

 

        @Override

        public void run() {

            System.out.println("当前执行的线程"+Thread.currentThread().getName());

        }

         

    }

}

 

3. Use Qurtz

Qurtz is very simple to use and supports more triggering mechanisms as a solution.

具体的应用可以查看官方文档:http://www.quartz-scheduler.org/documentation/quartz-2.2.x/tutorials/

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326154519&siteId=291194637