Timer and TimerTask detailed

Source: Internet
Author: User

1. Overview

A timer is a timer tool that is used to schedule a specified task in a background thread. It can schedule a task to execute once or repeatedly.
TimerTask an abstract class whose subclasses represent a task that can be scheduled by the timer.

A simple routine:

Import Java.util.Timer;
Import Java.util.TimerTask;

/**
* Simple Demo this uses Java.util.Timer to schedule a task to execute
* Once 5 seconds have passed.
*/

public class Reminder {
Timer timer;

Public Reminder (int seconds) {
timer = new timer ();
Timer.schedule (New Remindtask (), seconds*1000);
}

class Remindtask extends TimerTask {
Public void Run () {
System.out.println ("Time ' s up!");
Timer.cancel (); Terminate the timer thread
}
}

public static void Main (String args[]) {
System.out.println ("About to schedule task.");
New Reminder (5);
System.out.println ("Task scheduled.");
}
}


To run this small example, you will first see:

About to schedule task.

After 5 seconds you will see:

Time ' s up!

This small example illustrates some of the basic steps to implement and plan a task with a timer thread:

    • To implement a subclass of a custom TimerTask, the Run method contains the task code to execute, in this case the subclass is Remindtask.
    • Instantiate the Timer class and create a timers background thread.
    • Instantiates a Task object ( new RemindTask() ).
    • Develop an execution plan. Here, with the schedule method, the first parameter is the TimerTask object, and the second parameter indicates the delay time before execution starts (in milliseconds, 5000 is defined here). There is also a way to specify the execution time of a task, as the following example specifies that the task is performed at 11:01 p.m.:

Get the Date corresponding to 11:01:00 pm today.
Calendar calendar = Calendar.getinstance ();
Calendar.set (Calendar.hour_of_day, 23);
Calendar.set (Calendar.minute, 1);
Calendar.set (Calendar.second, 0);
Date time = Calendar.gettime ();

Timer = new timer ();
Timer.schedule (New Remindtask (), time);

2. Terminating the timer thread

By default, the program stays running as long as a program's timer thread is running. Of course, you can terminate a timer thread in the following four ways:

    • Call the timer's Cancle method. You can call this method from anywhere in the program, even in a timer task's Run method.
    • Make the timer thread a daemon thread (you can use the new timer (true) to reach this point when you create the timer), so that when the program has only daemon threads, it will automatically terminate the run.
    • When all the tasks related to the timer have been executed, delete all references to this timer object (NULL) so that the timer thread terminates.
    • Call the System.exit method to terminate the entire program (all threads).

The reminder example uses the first method. The second method cannot be used here, because it requires the program to remain running until the timer's task is completed, and if it is set to daemon, then when the main thread ends, the program only has the timer daemon thread, The program does not terminate when the timer thread executes the task.

Sometimes, the termination of a program is not only related to the timer thread. For example, if we use AWT to beep, then AWT will automatically create a non-daemon thread to keep the program running. The following code we have modified reminder, added the beeping function, so we need to join the SYSTEM.EXIT call to terminate the program.


Import Java.util.Timer;
Import Java.util.TimerTask;
Import Java.awt.Toolkit;

/**
* Simple Demo this uses Java.util.Timer to schedule a task to execute
* Once 5 seconds have passed.
*/

public class Reminderbeep {
Toolkit Toolkit;
Timer timer;

Public reminderbeep (int seconds) {
toolkit = Toolkit.getdefaulttoolkit ();
Timer = new timer ();
Timer.schedule (New Remindtask (), seconds*1000);
}

Class Remindtask extends TimerTask {
public void Run () {
System.out.println ("Time ' s up!");
Toolkit.beep ();
Timer.cancel (); Not necessary because we call System.exit
System.exit (0); Stops the AWT thread (and everything else)

}
}

public static void Main (String args[]) {
System.out.println ("About to schedule task.");
New Reminderbeep (5);
System.out.println ("Task scheduled.");
}
}


3. Perform a task repeatedly

Let's look at an example:

public class Annoyingbeep {
Toolkit Toolkit;
Timer timer;

Public Annoyingbeep () {
Toolkit = Toolkit.getdefaulttoolkit ();
Timer = new timer ();
Timer.schedule (New Remindtask (),
0,//initial delay
1*1000); Subsequent
rate

}

Class Remindtask extends TimerTask {
int numwarningbeeps = 3;

public void Run () {
if (Numwarningbeeps > 0) {
Toolkit.beep ();
System.out.println ("beep!");
numwarningbeeps--;
} else {
Toolkit.beep ();
System.out.println ("Time ' s up!");
Timer.cancel (); Not necessary because we call System.exit
System.exit (0); Stops the AWT thread (and everything else)
}
}
}
...
}


execution, you will see the following output:

Task scheduled.
Beep!
Beep! //one Second after the first beep
Beep! //one Second after the second beep
Time ' s up! //one Second after the third beep

Here, the schedule method with three parameters is used to specify that the task executes once every second. As listed below, all timer classes are used to develop a method for planning recurring tasks:

    • schedule(TimerTask task, long delay, long period)
    • schedule(TimerTask task, Date time, long period)
    • scheduleAtFixedRate(TimerTask task, long delay, long period)
    • scheduleAtFixedRate(TimerTask task, Date firstTime, long period)

When planning a recurring task, if you focus on the smoothness of the task execution, then use the schedule method, if you care about the frequency of the execution of the task, then use the Scheduleatfixedrate method. For example, the schedule method is used here, which means that the interval between all beep is at least 1 seconds, that is, if there is a beap that is late for some reason (not executed as planned), then all the remaining beep are deferred. If we want this program to terminate in just 3 seconds, whichever beep is delayed for whatever reason, then we need to use the Scheduleatfixedrate method so that when the first beep is late, Then the beep will be executed at the fastest speed (maximum compression interval).

4. Further analysis of schedule and Scheduleatfixedrate

(1) Schedule of 2 parameters The task is executed immediately when the scheduled execution time of the specified Scheduledexecutiontime<=systemcurrenttime is established. Scheduledexecutiontime does not change because of the excessive execution of a task.
(2) Schedule of 3 parameters when formulating a plan to execute a task repeatedly, the scheduled execution time for each execution of the task changes with the actual execution time of the previous one, that is, scheduledexecutiontime (n+1) = Realexecutiontime (nth time) +periodtime. That is, if the nth execution of a task, for some reason the execution time is too long, after the execution of the Systemcurrenttime>=scheduledexecutiontime (n+1), then do not wait for a moment, immediately execute the n+ 1 tasks, and the next n+2 task Scheduledexecutiontime (n+2) becomes realexecutiontime (n+1 times) +periodtime. plainly, this approach is more focused on keeping the interval stable.
(3) The scheduleatfixedrate of 3 parameters when formulating a plan to execute a task repeatedly, the scheduled execution time for each execution of the task is initially determined, i.e. scheduledexecutiontime (nth time) = Firstexecutetime+n*periodtime; If the nth execution of a task is for some reason the execution time is too long, after the execution of the Systemcurrenttime>=scheduledexecutiontime (nth + 1 times), then do not do period interval wait, immediately execute the N+1 task, and the next n+2 task of Scheduledexecutiontime (n+2) still firstexecutetime+ (n+2) * Periodtime This is the first time that a task is executed. plainly, this approach is more focused on maintaining the stability of the execution frequency.

5. Some issues of attention
      • Each timer only corresponds to a single thread.
      • The timer does not guarantee that the task executes very precisely.
      • The Timer class is thread-safe.

Timer and TimerTask detailed

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.