Implementation of Java timed scheduling task

Source: Internet
Author: User

Sometimes, we want the program to execute at some point in the future, and we want it to be repeated multiple times!

Therefore, we need to implement the timing scheduling function.

In Java, there are two classes that work together to implement scheduled scheduling: Java.util.Timer and Java.util.TimerTask

The timer can be understood as having and only one background thread scheduling multiple business threads at timed scheduled intervals

TimerTask can be understood as the writing of business logic

That is, thetimer dispatches the business logic inside the timertask according to a certain time frequency.

Below, by implementing how to get the program to execute in 2 seconds, to illustrate the implementation of the timer Scheduler code writing:

Timer timer=NewTimer (); Calendar Calendar=calendar.getinstance (); SimpleDateFormat SF=NewSimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); System.out.println ("Current time is" +Sf.format (Calendar.gettime ())); Timer.schedule (NewTimerTask () { Public voidrun () {Calendar Calendar=calendar.getinstance (); SimpleDateFormat SF=NewSimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); System.out.println ("The time to perform this task is" +Sf.format (Calendar.gettime ())); }        },2000);

Visible, is through the instantiation of the timer, call its schedule method to achieve scheduled scheduling.


The schedule is available in four different forms:

Schedule (Task,time);

Schedule (Task,time,period);

Schedule (Task,delay);

Schedule (Task,delay,period);

Where the taskis what we need to do, time is the moment when the task is first executed, and period is the interval at which a task is executed, and delay is the time before the first task is executed, in milliseconds.

So the end is writing the task code.

Here, using an inner class to illustrate, we write our own task code by rewriting the Run method .

The above basic realization of the timing scheduling task.

However, there are two problems:

1. What happens if we need the time to execute the task before the current time?

2. What happens if the execution time of our task is greater than the execution interval of the task?

For problem one, we can change the above run method slightly to know:

             Public void run () {                =calendar.getinstance ();                SimpleDateFormat SF=new simpledateformat ("Yyyy-mm-dd HH:mm:ss");                 -1);                System.out.println ("Time to perform this task is" +Sf.format (Calendar.gettime ()));            

The result is this:
Current time is 2017-05-21 10:25:
The time to perform this mission is 2017-05-21 10:25 :

The program chooses to execute immediately and still considers the delay when I reverse the time of the program by a second.

For question two, it can also be easily verified;

 timer.schedule (new TimerTask () { 
public void run () {calend AR calendar =calendar.getinstance (); SimpleDateFormat SF =new simpledateformat ("Yyyy-mm-dd HH:mm:ss" try {thread.sleep ( 3000 Span style= "color: #000000"); catch (interruptedexception e) { E.printstacktrace (); } System.out.println ( "The time to perform this task is" +sf.format (Calendar.gettime ())); }}, 1000,2000);

Output Result:
The current time is 2017-05-21 10:31:05
The time to perform this mission is 2017-05-21 10:31 :
The time to perform this mission is 2017-05-21 10:31 :
The time to perform this mission is 2017-05-21 10:31 :

Is it the same as the thought, the program will start executing relative to the point at which the last execution was completed, and then slowly lag behind.

After the discussion, schedule method, in fact, there is a timer inside a task to achieve the scheduling method, Scheduleatfixedrate,

Scheduleatfixedrate (Task,time,period);

Scheduleatfixedrate (Task,delay,period);

Regardless of the above two problems, the implementation process is similar to those two cases, because the scheduleatfixedrate implementation process has a certain degree of concurrency, in the actual implementation of small white feel more complex, not discussed ...

Finally, simply say,

Other important methods inside the timer:

Cancel (), terminates this timer, discards all currently scheduled tasks, or can be canceled separately, such as Task1.cancel ();
Purge () removes all canceled tasks from this timer's task queue, returning the number of tasks removed from the queue.

Other important methods within the Timetask:

Cancel (), cancels the task in the current timetask;
Scheduledexecutiontime () to return the time that this task has been scheduled to execute recently.

 

Implementation of Java timed scheduling task

Related Article

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.