Detailed Java Timing tasks

Source: Internet
Author: User

In our programming process, if we need to perform some simple timed tasks without complicated control, we can consider using the Timer Timer task in the JDK. The following LZ on its principles, examples and timer defects three aspects to parse the Java timer timer.

First, Introduction

A complete scheduled task in Java needs to be completed by a timer, timertask two classes. The API defines them as a Timer: A tool that a thread uses to schedule tasks to perform later in a background thread. You can schedule a task to execute once, or repeat it periodically. A task that is scheduled to be performed or performed repeatedly by Timertask:timer. We can understand that. A timer is a timer tool that is used to schedule a specified task in a background thread, and timertask an abstract class that represents a task that can be scheduled by a timer.

Timer class

In the tool class timer, there are four construction methods, each of which starts the timer thread, and the timer class ensures that multiple threads can share a single Timer object without external synchronization, so the timer class is thread safe. But since each timer object corresponds to a single background thread, which is used to execute all the timer tasks sequentially, our thread task execution should typically take a very short time, but because of special circumstances that cause a timer task to execute too long, he will "monopolize" the task execution thread of the timer , all subsequent threads must wait for it to execute, which delays the execution of the successor tasks, and causes these tasks to accumulate together, which we analyze later.

When the program initialization completes the timer, the timer task will follow our set time to execute, the timer provides the schedule method, this method has the multi-medium overloaded way to adapt the different situation, as follows:

Schedule (timertask task, Date time): Schedules the specified task to execute at the specified time.

Schedule (timertask task, Date Firsttime, long period): schedules the specified task to begin repeating fixed deferred execution at a specified time.

Schedule (timertask task, long delay): schedules the specified task to execute after a specified delay.

Schedule (timertask task, long delay, long period): schedules the specified task to start repeating fixed deferred execution from the specified delay.

At the same time, the Scheduleatfixedrate method is overloaded, and the Scheduleatfixedrate method is the same as schedule, except that their focus is different and the difference is analyzed later.

Scheduleatfixedrate (timertask task, Date Firsttime, long period): schedules the specified task to execute at a fixed rate that repeats at a specified time.

Scheduleatfixedrate (timertask task, long delay, long period): schedules the specified task to begin repeating a fixed rate of execution after the specified delay.

TimerTask

The TimerTask class is an abstract class that is scheduled for a task to be executed or repeated by a timer. It has an abstract method of the run () method, which is used to perform the actions to be performed by the corresponding timer task. Therefore, each specific task class must inherit TimerTask and then rewrite the run () method.

In addition, it has two non-abstract methods:

Boolean cancel (): Cancels this timer task.

Long Scheduledexecutiontime (): Returns the schedule execution time that this task has recently actually performed.

Second, instance 2.1, specify the delay time to perform scheduled tasks
public class TimerTest01 {    timer timer;    Public TimerTest01 (int time) {        timer = new timer ();        Timer.schedule (New TimerTaskTest01 (), time *);    }        public static void Main (string[] args) {        System.out.println ("Timer begin ...");        New TimerTest01 (3);}    } public class TimerTaskTest01 extends timertask{public    void Run () {        System.out.println ("TIME's Up!!!!");}    }

Operation Result:

Print first: Timer begin .... Print in 3 seconds: TIME's UP!!!!
2.2. Perform scheduled tasks at specified times
public class TimerTest02 {    timer timer;        Public TimerTest02 () {        Date time = GetTime ();        System.out.println ("time=" + time);        Timer = new timer ();        Timer.schedule (New TimerTaskTest02 (), time);    }        Public Date GetTime () {        Calendar calendar = calendar.getinstance ();        Calendar.set (Calendar.hour_of_day, one);        Calendar.set (Calendar.minute,);        Calendar.set (Calendar.second, XX);        Date time = Calendar.gettime ();                return time;    }        public static void Main (string[] args) {        new TimerTest02 ();}    } public class TimerTaskTest02 extends timertask{    @Override public    void Run () {        System.out.println (" Specify time to perform thread tasks ... ");}    }

When the time arrives at 11:39:00, the thread task executes, of course, more than that time!! The result of the execution is:

Specify time Time=tue June 11:39:00 CST 2014 specify time to perform thread tasks ...
2.3. Cycle through timed tasks at specified intervals after a specified time delay
public class TimerTest03 {    timer timer;        Public TimerTest03 () {        timer = new timer ();        Timer.schedule (New TimerTaskTest03 (), +,);    }        public static void Main (string[] args) {        new TimerTest03 ();}    } public class TimerTaskTest03 extends timertask{    @Override public    void Run () {        date date = new Date (this.sche Duledexecutiontime ());        System.out.println ("This time the thread is executing:" + date);}    }

Operation Result:

The time this thread was executed is: Tue June 21:19:47 CST 2014 the time this thread was executed is: Tue June 21:19:49 CST 2014 this time the thread was executed: Tue June 21:19:51 CST 2014 this time The time to execute the thread is: Tue June 21:19:53 CST 2014 the time this thread was executed is: Tue June 21:19:55 CST 2014 this time the thread was executed: Tue June 21:19:57 CST 2014 .... .............

For this thread task, if we don't stop the task, he will keep running.

For the above three instances, LZ is just a simple demonstration, but also does not explain the Scheduleatfixedrate method of example, in fact, the method is the same as the schedule Method!

2.4. Analysis of schedule and Scheduleatfixedrate

1,Schedule (timertask task, Date time), schedule (timertask task, long delay)

For both methods, if the specified schedule execution time scheduledexecutiontime<= Systemcurrenttime, the task is executed immediately. Scheduledexecutiontime does not change because of the excessive execution of a task.

2,Schedule (timertask task, Date Firsttime, long period), schedule (timertask task, long delay, long period)

These two methods are a bit different from the above two, the timer task that preceded the timer will be delayed because the previous task has been executing for a long time. In both methods, the scheduled time of each task executed will change with the actual time of the previous task, i.e. Scheduledexecutiontime (n+1) =realexecutiontime (n) +periodtime. That is, if the nth task causes this execution time process due to a certain situation, and finally leads to systemcurrenttime>= Scheduledexecutiontime (n+1), this is the N+1 task and will not be executed because of the time, He waits for the nth task to be executed before it executes, so it is bound to cause the n+2 implementation to implement Scheduledexecutiontime release change that is Scheduledexecutiontime (n+2) = Realexecutiontime (n+1) +periodtime. Therefore, these two methods pay more attention to the stability of the preservation interval time.

3,scheduleatfixedrate (timertask task, Date Firsttime, long period), Scheduleatfixedrate (timertask task, long Delay, long period)

The emphasis of scheduleatfixedrate and schedule method is different, the schedule method focuses on the stability of the preservation interval time, and the Scheduleatfixedrate method is more focused on maintaining the stability of the execution frequency. Why do you say so, for the following reasons? In the schedule method, due to the delay of the previous task, the timing task delay is followed, and the Scheduleatfixedrate method does not, if the nth task takes too long to execute systemcurrenttime>= Scheduledexecutiontime (n+1), then does not do any waiting he will immediately execute the N+1 task, so the Scheduleatfixedrate method execution time calculation method differs from schedule, Instead of Scheduledexecutiontime (n) =firstexecutetime +n*periodtime, the calculation method is never changed. So scheduleatfixedrate more focused on maintaining the stability of the execution frequency.

Third, the timer's defect 3.1, the timer flaw

The timer timer can be timed (to perform a task at a specified time), delayed (performing a task with a delay of 5 seconds), periodically performing a task (performing a task every 1 seconds), but there are some flaws in the timer. First, the timer's support for scheduling is based on absolute time, not relative time, so it is very sensitive to changes in system time. Secondly, the timer thread will not catch the exception, if TimerTask throws an unchecked exception will cause the timer thread to terminate, and the timer will not re-resume the execution of the thread, he will mistakenly think the entire timer thread will be canceled. At the same time, the timertask that have been scheduled to be executed will no longer be executed, and the new task cannot be dispatched. Therefore, if TimerTask throws an unchecked exception, the timer will produce unpredictable behavior.

1, timer management time delay defects

The preceding timer will only create a thread task when performing a timed task, and if there are multiple threads, some of the defects will occur if one of the threads causes the thread task to take too long to perform for some reason, exceeding the interval of two tasks:

public class TimerTest04 {private timer timer;           public long start;        Public TimerTest04 () {This.timer = new timer ();    Start = System.currenttimemillis (); } public void Timerone () {Timer.schedule (new TimerTask () {public void run () {Sys                Tem.out.println ("Timerone invoked, the time:" + (System.currenttimemillis ()-start));    try {thread.sleep (4000);                Thread hibernation (interruptedexception e) {e.printstacktrace ();    }}}, 1000); } public void Timertwo () {Timer.schedule (new TimerTask () {public void run () {Sys            Tem.out.println ("Timerone invoked, the time:" + (System.currenttimemillis ()-start));    }}, 3000);                public static void Main (string[] args) throws Exception {TimerTest04 test = new TimerTest04 ();        Test.timerone ();Test.timertwo (); }}

According to our normal thinking, Timertwo should be executed after 3s, the result should be:

Timerone invoked, the Time:1001timerone invoked, the time:3001

But it backfired, timerone because sleep (4000), sleep 4s, while the timer inside is a thread, resulting in the time required to timeone more than the interval time, the result:

Timerone invoked, the Time:1000timerone invoked, the time:5000

2. Timer throws abnormal defect

If TimerTask throws Runtimeexception,timer, all tasks will be terminated. As follows:

public class TimerTest04 {    private timer timer;        Public TimerTest04 () {        This.timer = new timer ();    }        public void Timerone () {        timer.schedule (new TimerTask () {public            void run () {                throw new runtimeexception (); c8/>}}        , +);    }        public void Timertwo () {        timer.schedule (new TimerTask () {public                        void run () {                System.out.println (" Will I execute it?? ");}}        , +);    }        public static void Main (string[] args) {        TimerTest04 test = new TimerTest04 ();        Test.timerone ();        Test.timertwo ();    }}

Run Result: Timerone throws an exception that causes the Timertwo task to terminate.

Exception in Thread "Timer-0" Java.lang.RuntimeException at    Com.chenssy.timer.timertest04$1.run ( timertest04.java:25) at    Java.util.TimerThread.mainLoop (timer.java:555) at    Java.util.TimerThread.run ( timer.java:505)

For the timer flaw, we can consider Scheduledthreadpoolexecutor to replace. The timer is based on absolute time, is sensitive to system time, while Scheduledthreadpoolexecutor is based on relative time; the timer is a single thread inside, and Scheduledthreadpoolexecutor is a thread pool inside. , so multiple tasks can be supported for concurrent execution.

3.2, replace the timer with Scheduledexecutorservice

1, solve the problem one:

public class Scheduledexecutortest {private Scheduledexecutorservice scheduexec;        public long start;          Scheduledexecutortest () {this.scheduexec = Executors.newscheduledthreadpool (2);    This.start = System.currenttimemillis ();                } public void Timerone () {Scheduexec.schedule (new Runnable () {public void run () {                System.out.println ("Timerone,the Time:" + (System.currenttimemillis ()-start));                try {thread.sleep (4000);                } catch (Interruptedexception e) {e.printstacktrace ();    }}},1000,timeunit.milliseconds);                } public void Timertwo () {Scheduexec.schedule (new Runnable () {public void run () {            System.out.println ("Timertwo,the Time:" + (System.currenttimemillis ()-start));    }},2000,timeunit.milliseconds);        } public static void Main (string[] args) {Scheduledexecutortest test = new Scheduledexecutortest ();        Test.timerone ();    Test.timertwo (); }}

Operation Result:

Timerone,the time:1003timertwo,the time:2005

2, solve the problem two

public class Scheduledexecutortest {    private  scheduledexecutorservice scheduexec;        public long start;        Scheduledexecutortest () {        this.scheduexec =  Executors.newscheduledthreadpool (2);          This.start = System.currenttimemillis ();    }        public void Timerone () {        scheduexec.schedule (new Runnable () {public            void run () {                throw new RuntimeException ();            }        },1000,timeunit.milliseconds);    }        public void Timertwo () {        scheduexec.scheduleatfixedrate (new Runnable () {public            void run () {                System.out.println ("Timertwo invoked ...");            }        },2000,500,timeunit.milliseconds);        public static void Main (string[] args) {        scheduledexecutortest test = new Scheduledexecutortest ();        Test.timerone ();        Test.timertwo ();    }}

Operation Result:

Timertwo invoked ... timertwo invoked ... timertwo invoked ... timertwo invoked .... timertwo invoked ..... timerTwo in .......

Reference: http://blog.csdn.net/lmj623565791/article/details/27109467

Detailed Java Timing tasks

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.