The use of the Java timer timer.

Source: Internet
Author: User
Tags dateformat

First, the concept of scheduling task function in Java is the main use of the Timer object, which in the internal use of multi-threaded way to handle, so it and multithreading technology is very large association.      In the JDK, the timer class is primarily responsible for the ability to schedule tasks, that is, to start a task at a specified time, but the class that encapsulates the task is the TimerTask class. Customize the task you want to perform by inheriting the TimerTask class and implementing the Run () method:
 Public class extends timertask {    @Override    publicvoid  run ()    {        =  TimeUtil.df.get ();        System.out.println ("My task ran" + Dateformat.format (new  Date ()));}    }

Run the task at execution time by executing timer.schedule (TimerTask task,date times):

 Public class Run {    privatestatic timer timer=new  timer ();      Public Static void throws parseexception    {        timer.schedule(new mytask (), TimeUtil.df.get (). Parse ("2017-09-14 09:19:30"));}    }

Note: The time Conversion Tool class ensures thread safety:

 Public class timeutil{    publicstaticfinalnew threadlocal<dateformat> () {        @Override        protected  DateFormat InitialValue () {            return  New SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");}}    ;}
Time Conversion Tool classSecond, the timer kind of attention matters

1, Create a Timer object is a new start a thread, but this newly-started thread, not the daemon, it has been running in the background, by the following can set the newly-started Timer thread to the daemon thread.

Private Static Timer timer=New timer (true);

2, in advance: When the scheduled time is earlier than the current time, the task is immediately run.

3 . Delay: TimerTask is run sequentially in a queue, so the time to execute may not be the same as the time you expect, because the previous task may take a long time and the subsequent task will run for a delay. The time to start a deferred task is based on the "End time" of the previous task

4, periodic operation: Timer.schedule (TimerTask task,date firsttime,long period) from firsttime every period milliseconds to perform a task:

5,Schedule (timertask task,long delay) The current time is the reference time, based on this time delay in the number of milliseconds to execute a timertask task.

6.Schedule (TimerTask task,long Delay,long period) The current time is the reference time, on which a delay in the number of milliseconds, and then an infinite number of times a certain interval of time to perform a task.

7. What is the difference between the cancel () of the timer and the Cancel () of TimerTask?

As mentioned earlier, the execution of a task is executed sequentially in the same way as the column, Timertask.cancel () refers to canceling the current task from the task to joins. The Timer.cancel () value is to cancel all tasks in the current task queue. It is important to note that A Timer's cancel () sometimes does not necessarily stop the execution of the scheduled task, but executes normally. This is because the Cancel () method in the Timer class sometimes does not scramble to the queue lock, so the tasks in the TimerTask class continue to execute normally.

Iii. scheduleatfixedrate (timertask task,date Firsttime,long period) and schedule (TimerTask task,date Firsttime,long period) Difference

Same point:

1. Method schedule and method Scheduleatfixedrate are executed sequentially, so non-thread-safe situations are not considered.

2, Method schedule and method Scheduleatfixedrate if the time to perform the task is not delayed, the next task's execution time is calculated by the time of the last task's "start".

3, Method schedule and method Scheduleatfixedrate if the time to execute the task is delayed, then the execution time of the next task is referred to the time of the last task "end" to calculate.

Different points:

Methods schedule and Method Scheduleatfixedrate in the use of the basic no difference, that is, Scheduleatfixedrate has the pursuit of execution, what meaning? If the task is interrupted during a periodic run, Scheduleatfixedrate will attempt to make up the task that was previously dropped. and schedule is no matter, then run the next task on the line, you can refer to this blog , written very vivid.

The use of the Java timer 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.