Java Timers Task Timer usage

Source: Internet
Author: User
Tags dateformat

In the project development, often encountered the need to implement a number of scheduled operations tasks, written many times, but each time, will always have some details to forget, and later thought may not be summed up the reason, so today's small series to summarize may be forgotten small points:

1. public void Schedule (TimerTask task,date time) In this method, such as when it was started, the system will be executed directly once after it is started.
    Words not much directly on the code
 PackageCom.test.timer.task;ImportJava.text.DateFormat;ImportJava.text.SimpleDateFormat;ImportJava.util.Calendar;Importjava.util.Date;ImportJava.util.Timer;ImportJava.util.TimerTask;Importorg.junit.Test;/*** * Some methods of implementing timers in Java * *@authorJimi **/ Public classTesttask {Private StaticTimer timer =NewTimer (); Private StaticDateFormat DateFormat =NewSimpleDateFormat ("HH:mm:ss");  Public Static voidMain (string[] args) {Calendar Calendar=calendar.getinstance (); intYear =Calendar.get (calendar.year); intmonth =Calendar.get (Calendar.month); intDay =Calendar.get (Calendar.day_of_month); Calendar.set (Year,month,day,20,35,00); //If this time is past, the start will be executed immediately.Timer.schedule (NewTimerTask () {@Override Public voidrun () {System.out.println ("Fixed time to perform task:" + Dateformat.format (NewDate ()));    }}, Calendar.gettime ()); }    }
The code I specified on the day of the 20:35 execution, the results after the start of the program are as follows:


Can see my program is executed at 20:40:47, has exceeded my set of 20:35 00 seconds, so start directly after the execution.

Differences between schedule (TimerTask Task,long Delay,long period) and scheduleatfixedrate (TimerTask task,long Delay,long period) methods
In short, it's timed execution . Scheduleatfixedrate is not affected by the outside world, if a timertask execution time exceeds the scheduled execution period, the next execution time will not be affected by the task execution time,
will still be executed at the specified time, and
Schedule will be affected, directly on the code to see:

 PackageCom.test.timer.task;ImportJava.text.DateFormat;Importjava.text.ParseException;ImportJava.text.SimpleDateFormat;Importjava.util.Date;ImportJava.util.Timer;ImportJava.util.TimerTask;/*** * Some methods of implementing timers in Java * *@authorJimi **/ Public classTesttask {Private StaticTimer timer =NewTimer (); Private StaticDateFormat DateFormat =NewSimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); Private Static intindex = 0;  Public Static voidMain (string[] args)throwsparseexception{//Fixed rateTimer.scheduleatfixedrate (NewTimerTask () {@Override Public voidrun () {index++; if(index% 5 = = 0){                            Try{Thread.Sleep (5000); } Catch(interruptedexception e) {e.printstacktrace (); }} System.out.println ("Execute once every 4 seconds:" + Dateformat.format (NewDate ())); }                }, 0, 4000); }    }

As you can see from the code, when the index is a multiple of 5, the program sleeps for 5 seconds, and we take a look at the results of the execution.

Executes every 4 seconds: 2018-08-10 19:12:09
Executes every 4 seconds: 2018-08-10 19:12:13
Executes every 4 seconds: 2018-08-10 19:12:17
Executes every 4 seconds: 2018-08-10 19:12:21
Executes every 4 seconds: 2018-08-10 19:12:30
Executes every 4 seconds: 2018-08-10 19:12:30
Executes every 4 seconds: 2018-08-10 19:12:33
Executes every 4 seconds: 2018-08-10 19:12:37
Executes every 4 seconds: 2018-08-10 19:12:41
Executes every 4 seconds: 2018-08-10 19:12:50
Executes every 4 seconds: 2018-08-10 19:12:50
Executes every 4 seconds: 2018-08-10 19:12:53
Executes every 4 seconds: 2018-08-10 19:12:57
Executes every 4 seconds: 2018-08-10 19:13:01
Executes every 4 seconds: 2018-08-10 19:13:10
Executes every 4 seconds: 2018-08-10 19:13:10

We can see that the fifth and sixth times are running simultaneously, and the seventh time is not 4 seconds on the base of the 19:12:30, but the pre-calculated time after the program starts, which is 19:12:33 seconds. It can be seen that the execution time of the scheduleatfixedrate is performed at a predetermined fixed rate and does not affect the subsequent scheduling time because of a delay.

Let's take a look at the code and implementation of schedule.

 PackageCom.test.timer.task;ImportJava.text.DateFormat;Importjava.text.ParseException;ImportJava.text.SimpleDateFormat;Importjava.util.Date;ImportJava.util.Timer;ImportJava.util.TimerTask;/*** * Some methods of implementing timers in Java * *@authorJimi **/ Public classTesttask {Private StaticTimer timer =NewTimer (); Private StaticDateFormat DateFormat =NewSimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); Private Static intindex = 0;  Public Static voidMain (string[] args)throwsparseexception{//non-fixed rateTimer.schedule (NewTimerTask () {@Override Public voidrun () {index++; if(index% 5 = = 0){                    Try{Thread.Sleep (5000); } Catch(interruptedexception e) {e.printstacktrace (); }} System.out.println ("Execute once every 4 seconds:" + Dateformat.format (NewDate ())); }        }, 0, 4000); }    }

Implementation of the following

Executes every 4 seconds: 2018-08-10 19:17:12 is executed every 4 seconds:2018-08-10 19:17:16 every 4 seconds:2018-08-10 19:17:20  Executes every 4 seconds: 2018-08-10 19:17:24 is executed every 4 seconds:2018-08-10 19:17:33 every 4 seconds:2018-08-10 19:17:33  Executes every 4 seconds: 2018-08-10 19:17:37 is executed every 4 seconds:2018-08-10 19:17:41 every 4 seconds:2018-08-10 19:17:45  Executes every 4 seconds: 2018-08-10 19:17:54 executes every 4 seconds:2018-08-10 19:17:54 every 4 seconds:2018-08-10 19:17:58

can see schedule After the completion of the 5th and 6 missions, the 7th time is based on the schedule 4 seconds after the execution, visible schedule during the task execution, if a task is delayed, then the successor task will follow the delay time to recalculate the scheduled execution time.

Well, the small part of the code here today, the following may also be introduced to spring's scheduled tasks, as well as the Spring+quartz implementation of the scheduled tasks.




Java Timers Task Timer usage

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.