Timers in Java Timer

Source: Internet
Author: User

 

Java.util.Timer is a utility class that is used to schedule a thread so that it can be executed at some point in the future. The Java Timer class can schedule a task to run once, or run on a regular basis.

Java.util.TimerTask is an abstract class that implements the Runnable interface. We need to extend this class to create our own timertask, which can be dispatched using the Java Timer class inside the TimerTask.

The Timer class is thread-safe, and multiple processes can share the same timer object without the need for an external synchronization mechanism. The Timer class uses Java.util.TaskQueue to add tasks at specified intervals and only one thread can execute timertask at any time. For example, to create a timer that runs every 10 seconds, but the execution time of a single thread takes 20 seconds, the timer object will continue to add the task to the queue, and once the task finishes, it notifies the queue and another thread starts execution.

The Timer class uses the wait and notify methods of the object to dispatch tasks.

Here is an example of using a timer and TimerTask:

 Packagecom.journaldev.threads;Importjava.util.Date;ImportJava.util.Timer;ImportJava.util.TimerTask; Public classMytimertaskextendsTimerTask {@Override Public voidrun () {System.out.println ("Timer task started at:" +NewDate ());        Completetask (); System.out.println ("Timer task finished at:" +NewDate ()); }     Private voidCompletetask () {Try {            //assuming it takes secs to complete the taskThread.Sleep (20000); } Catch(interruptedexception e) {e.printstacktrace (); }    }      Public Static voidMain (String args[]) {timertask TimerTask=NewMytimertask (); //running timer task as daemon threadTimer timer =NewTimer (true); Timer.scheduleatfixedrate (TimerTask,0, 10*1000); System.out.println ("TimerTask started"); //Cancel after sometime        Try{Thread.Sleep (120000); } Catch(interruptedexception e) {e.printstacktrace ();        } timer.cancel (); System.out.println ("TimerTask cancelled"); Try{Thread.Sleep (30000); } Catch(interruptedexception e) {e.printstacktrace (); }    }}

Note that a thread execution takes 20 seconds, but the timer object dispatches the task every 10 seconds. The output of the program is as follows.

timertask startedtimer Task started At:mon Mar12:58:24 CST 2014Timer task finished At:mon Mar12:58:44 CST 2014Timer Task started At:mon Mar12:58:44 CST 2014Timer task finished At:mon Mar12:59:04 CST 2014Timer Task started At:mon Mar12:59:04 CST 2014Timer task finished At:mon Mar12:59:24 CST 2014Timer Task started At:mon Mar12:59:24 CST 2014Timer task finished At:mon Mar12:59:44 CST 2014Timer Task started At:mon Mar12:59:44 CST 2014Timer task finished At:mon Mar13:00:04 CST 2014Timer Task started At:mon Mar13:00:04 CST 2014timertask cancelledtimer task finished At:mon Mar13:00:24 CST 2014

The output confirms that if a task has already been executed, the timer waits for it to finish and once the task execution is finished, the timer object will start the next task in the queue again.

The timer object can run related tasks as a daemon thread. The Cancel () method of the timer is used to terminate the timer and discard the task to be dispatched. However, the timer does not interfere with the currently executing task and let it end. If the timer is used to execute a daemon thread, it waits for all user threads to terminate, regardless of whether or not it is canceled.

The Timer class contains some sechedule () methods to schedule a task to run once or after a specified time. There are also some scheduleatfixedrate () methods for running tasks after a certain interval

When you use the timer to schedule a task, you must make sure that the time interval exceeds the normal program run time, or the task queue size will continue to grow and the program will not stop.

   

Original link: Journaldev translation: Importnew.com-liken
Link: http://www.importnew.com/9978.html
[Reprint please keep the source, translator and translation links.] ]

Timers in Java Timer

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.