Java Timer (timed call, implementation fixed time execution)

Source: Internet
Author: User

The function of a timed call is recently required. You can make timed calls through the Java Timer class, and here are some of the relevant knowledge about the timer.

In fact, the timer is a scheduler, and TimerTask is just a implementation of the run method of a class, and the specific timertask need to be implemented by yourself, such as:

New Timer (); Timer.schedule (new  timertask () {        publicvoid  run () {            System.out.println ("11232");         200000, 1000);

Here directly implement a timertask (of course, you can implement multiple timertask, multiple timertask can be dispatched by a timer will be assigned to a number of timer, the following will say that the implementation mechanism of the timer is the internal scheduling mechanism), Then write the Run method, after 20s execution, execute once per second, of course, you through a timer object to manipulate multiple timertask, in fact, timertask itself is meaningless, just and timer set operation of an object, implement it must have corresponding to the Run method, In order to be called, he doesn't even need to implement runnable, because this often confuse, why? is also the focus of this article.

When it comes to the principle of the timer, let's look at some common methods in the timer:

1, this method is to dispatch a task, after delay (ms) to start scheduling, only dispatched once.

     Public void Long delay)

2. Dispatched at the specified point in time.

 Public void Schedule (timertask task, Date time)

3, this method is to dispatch a task, after delay (MS) to start the dispatch, after each dispatch, the minimum waiting for period (ms) to start scheduling.
 Public void Long Long period)

4, similar to the previous method, the only difference is that the second parameter passed in is the time of the first dispatch.
 Public void Long period)

5, scheduling a task, after delay (ms) began scheduling, and then every period (ms) again dispatched, looks and methods: Schedule is the same, not actually, later you will see according to the source code, schedule in the next execution time, is calculated by the current time (before the task execution) + time slice, and scheduleatfixedrateThe method is based on the time currently required to execute (that is, the time that should be calculated now) + The time slice, which is the actual time of the run, and the latter is the theoretical point of time, for example: ScheduleThe time slice is 5s, so in theory 5, 10, 15,These time slices are dispatched, but if it is not dispatched due to some CPU requisition, if it waits until the 8s is first dispatched, then ScheduleThe next time the method is calculated should be 13s instead of 10s, so it is possible to get to 20s be dispatched one or more times less, while scheduleatfixedrateThe method is each time the theory calculates the next time to be scheduled to order, if the 8s is dispatched, then the calculation should be 10s, so it is 2s from the current time, then the scheduling queue sequencing, will be prioritized dispatch, then Minimizing the drain scheduleThe situation.
 Public void Long Long period)

6, the method ibid, the only difference is that the first scheduling time is set to a date time, rather than a time slice of the current time, we will detail these in the source code.
 Public void scheduleatfixedrate (timertask task, Date firsttime,long period)

Source SectionFirst look at the timer Construction MethodThere are several: Construction Method 1: Non-parametric construction method, simply construct a thread name with Tiemer as a prefix:
 Public Timer () {    this ("timer-" + serialnumber ());} 

The thread that is created is not the main course, and the timer ends automatically after the main thread ends without using Cancel to complete the timer.

Construction Method 2: passed in as a background thread,The background thread is automatically logged off when and only if the process ends.
 Public Timer (boolean  isdaemon) {    this ("timer-" + serialnumber (), Isdaemon);} 

The other two construction methods are responsible for passing in names and starting the timer:

 Public Boolean Isdaemon) {      thread.setname (name);      Thread.setdaemon (Isdaemon);      Thread.Start ();  }

Here's a thread, which is obviously a thread that is wrapped in a timer class, and we look at the definition of this thread:

Private New TimerThread (queue);

And the definition of the TimerThread section is:
And the definition of the TimerThread section is:

See here, thetimer inside wraps a thread that is used to make a schedule that is independent of the external thread, and TimerThread is a default type, which is not referenced by defaults and is used by the timer itself.

and then look at the attributes   .In addition to the thread mentioned above, there is a very important property:
Private New Taskqueue ();

Look at the name to know is a queue, the queue inside can guess first guess what is, then probably should be I want to dispatch the task, first recorded, then continue to look down:

There is also a property that is:Threadreaper, it is the object type, just rewrite the Finalize method, is for garbage collection, the corresponding information is recycled, to do GC callback, that is, when the timer thread died for some reason, but not cancel, The information inside the queue needs to be emptied out, but we usually don't think about it, so we know what Java is doing with this method. next look at the implementation of the scheduling method:For the above 6 scheduling methods, we do not enumerate each, why wait for you to know:

Look at the method:

 Public void Long delay)

The source code is as follows:

 1  public  void  Schedule (timertask task, long   delay) { 2  if  (Delay < 0)  3  throw  new  illegalargumentexception ("negative delay."  4  sched (Task, System.currenttimemillis () +delay, 0); 5 } 

Here another method is called, the task is passed in, and the first argument passed in to System.currenttimemillis () +delay is visible as the point in time for the first time to execute (if the date is passed in, it is the object. GetTime (), So the introduction of several methods of the date is not to say more, and the third parameter passed 0, here can be guessed either the time slice, or the number of what, but will know what it is; Also on the method: Sched content We don't have to go to see him, first look at how the overloaded method is done

Then look at the method:
 Public void long delay,long period)

The source code is:

 public  void  Schedule (timertask Task, long  delay,  period) { if  (Delay < 0)  throw  new  IllegalArgumentException ("negative delay.")        );  if  (period <= 0)  throw  new  illegalargumentexception ("non-positive period."        );    Sched (Task, System.currenttimemillis ()  +delay,-period); }

It seems also called the method sched to complete the schedule, and the method is the only time the difference is to increase the incoming period, and the first incoming is 0, so determine this parameter is the time slice, not the number of times, note that the period in this added a negative, that is, take the reverse, That is, we start to pass 1000, when the call Sched will become-1000, in fact, after reading the source you will find that this is a foreigner for a number of understanding, and not have any special meaning, so read the source of the time also have these difficulties.

The last way to look at this is:
 Public void scheduleatfixedrate (timertasktask,long delay,long period)

The source code is:

 public  void  scheduleatfixedrate ( TimerTask task, long  delay, long   period) { if  (Delay < 0) 
    throw  new  IllegalArgumentException ("negative delay.")       );  if  (period <= 0)  throw  new  illegalargumentexception ("non-positive period."       );   Sched (Task, System.currenttimemillis ()  +delay, period); }

The only difference is that in the period did not take the opposite, in fact, you finally read the source, the above is not any special meaning, foreigners do not want to add a parameter to represent Scheduleatfixedrate, Most of the logic code in Scheduleatfixedrate and schedule is consistent, so the range of parameters is used as a distinguishing method, that is, when you pass in a parameter that is not a positive number, You call the schedule method is just to get the function of Scheduleatfixedrate, and call Scheduleatfixedrate method is exactly the function of schedule method, hehe, these discussions are meaningless, discuss the essence and focus:

Look at the implementation of the Sched method:

Private voidSched (timertask task,LongTimeLongperiod) {        if(Time < 0)            Throw NewIllegalArgumentException ("Illegal execution time."); synchronized(queue) {if(!thread.newtasksmaybescheduled)Throw NewIllegalStateException ("Timer already cancelled.")); synchronized(task.lock) {if(Task.state! =timertask.virgin)Throw NewIllegalStateException ("Task already scheduled or cancelled"); Task.nextexecutiontime=Time ; Task.period=period; Task.state=timertask.scheduled;            } queue.add (Task); if(queue.getmin () = =Task) queue.notify (); }    }

Queue for a queues, we do not look at his data structure, see him in this operation, the synchronization occurred, so at the timer level, this is thread-safe, and finally the task-related parameters assigned value, mainly including Nextexecutiontime (Next execution time), period (time slice), state, then put it into the queue, do a notify operation, why do notify operation? Look at the code behind you and you'll know.

In a nutshell, here is the process of putting a task into a queue, at which point you might be interested in the structure of the queues, so let's take a look at the structure of the queue property Taskqueue:

class taskqueue {     privatenew timertask[128];      Private int size = 0;

Visible, Taskqueue structure is very simple, for an array, plus a size, a bit like ArrayList, is not the length of 128, of course, is not, ArrayList can be expanded, it can, just will cause memory copy, so a timer, As long as the internal task number of not more than 128 is not caused by the expansion of the internal supply of Add (timertask), size (), getmin (), get (int), removemin (), quickremove (int), Reschedulemin (Long NewTime), IsEmpty (), clear (), fixup (), Fixdown (), heapify ();

   

Practice Section: 1. You must override the Run method by inheriting TimerTask.
 Public class extends timertask{    @Override    publicvoid  run ()    {        null ;         New SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss. SSS ");        System.out.println ("Current time:" + Sdf.format (new  Date ()));            }    }

 Public classtesttask{ Public Static voidMain (string[] args) {Timer T=NewTimer ();//set up a timer objectMyTask task =NewMyTask ();//Defining TasksT.schedule (task, 1000,2000);//set the execution of the task, starting in 1 seconds and executing once every 2 secondsCalendar Cal=calendar.getinstance (); Cal.set (Calendar.minute,30); T.schedule (Task, Cal.gettime (),2000); }}

2, through anonymous internal class implementation

New Timer ();          Timer.scheduleatfixedrate (new  timertask () {                  publicvoid  run () {                                          System.out.println ("abc");                  }           1000, 1000);

Thanks: Thank you for your patience and reading!

Java Timer (timed call, implementation fixed time execution)

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.