Timer and Timertask

xiaoxiao2021-03-06  37

The following is based on

The Javatm Tutorial and related API DOC translation for future reference:

Overview

Timer is a timer tool to perform a specified task in a background thread plan. It can schedule a task or repeated multiple times. TIMERTASK A abstract class, its subclass represents a task that can be programmed by the Timer. Simple routine:

import java.util.Timer; import java.util.TimerTask;. / *** Simple demo that uses java.util.Timer to schedule a task to execute * once 5 seconds have passed * / public class Reminder {Timer timer; public Reminder (int seconds) {time = new timer (); timer.schedule (new remindtask (), seconds * 1000);} Class Remindtask Extends Timertask {Public Void Run () {System.out.Println ("Time's Up!" ); Time.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.");}}

When you run this small example, you will first see:

About to schedule task.5 seconds later you will see: Time's Up!

This small example can illustrate some basic steps to implement a task with Timer threads:

Implement custom Timertask subclasses, RUN methods contain task code to be executed, in this example, this subclass is Remindtask. Instantiate the Timer class and create a timer backbone thread. Instantiate the task object (New Remindtask ()). Develop an execution plan. Here is the SCHEDULE method, the first parameter is the Timertask object, and the second parameter indicates the delay time before the start of execution (the unit is MilliseConds, which defines 5000). There is also a method to specify the execution time of the task, such as the following example, specifying the task at 11:01 p.m. Execute:

// Get the date corrence (Calendar. Hour_of_day, 23); Calendar.Minute, 1); Calendar.Minute, 1); Calendar.Minute, 1); Calendar.Set ( Calendar.second, 0); Date Time = Calendar.gettime (); Timer = New Timer (); Timer.Schedule (New Remindtask (), Time);

2. Terminate Timer Threads

By default, as long as a program's Timer thread is running, then this program will remain run. Of course, you can terminate a TIMER thread by four ways:

Call Timer's CANCLE method. You can call this method from any part of the program, even in a Timer Task's RUN method. Let the Timer thread become a daemon thread (you can use New Timer when you create Timer), so when the program only has the daemon thread, it will automatically terminate. When all TIMER-related task is executed, remove the references for all Timer objects (set up null) so that the Timer thread will also terminate. Call the System.exit method to terminate the entire program (all threads).

The example of Reminder uses the first way. Here, you cannot use the second method, because the program is required to keep running until Timer's task execution is complete, if it is set to Daemon, then when the main thread is over, the program only remains the daemon thread, so the program does not wait for Timer. Thread execution task is terminated. Sometimes, the termination of the program is not only related to the TIMER thread. For example, if we use the AWT to beep, AWT automatically creates a non-DAEMON thread to keep the program. The following code We modified the Reminder and joined the beeping function, so we need to add the SYSTEM.EXIT to terminate the program.

import java.util.Timer; import java.util.TimerTask; import java.awt.Toolkit; / *** Simple demo that 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) /////////// ' "Task Scheduled.");}}

3. Enter a task repeatedly

First 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)}}} ...} is executed, you will see the following output:

Task Scheduled.beep! Beep! // One Second After the first beepbeep! // one second after the second beeptime's up! // one second after the third beep here uses three parameters Schedule method to specify every one of Task Second to execute once. The following is a method for all TIMER classes to make a plan to perform Task:

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 you plan to repeatedly execute the task, if you pay attention to the smoothing of the task, use the Schedule method if you care about the execution frequency of the task, use the ScheduleatFixedRate method. For example, here is used here, which means that the time interval between all beep is at least 1 second, that is, if there is a BEAP because some reason is late (not performed as planned), then all BEEP Be delayed. If we want this program to terminate after 3 seconds, no matter which beep is delayed, then we need to use the ScheduleatFixedrate method, so when the first Beep is late, then the back BEEP will be fastest Speed ​​is closely performed (maximum compression interval time). 4. Further analysis of Schedule and ScheduleatFixedRate

(1) Two parameters of Schedule when developing a task plan,

If the specified plan execution time scheduledexecutionTIME <= SystemCurrentTime, Task will be executed immediately. ScheduledExecutionTime does not change because of excessive execution of a Task. (2) Schedule of 3 parameters When developing repeatedly executing a Task plan, each execution time executing this task changes with the previous actual implementation time, that is, ScheduledExecutionTime (N 1) = RealExecutionTime (Nth) PeriodTime. That is to say, when the NASK is executed, for some reason, the execution time is too long, the SYSTEMCURRENTTIME> = ScheduledexecutionTime (Nth 1) is executed at this time, immediately perform the first N 1 time TASK, and the next N 2 times Task ScheduledExecutionTime (n 2 times) becomes RealExecutionTIME (Nth 1) PeriodTime. To put it bluntly, this method pays more attention to the stability of the maintenance interval. (3) ScheduleatFixedRate of 3 parameters When developing a Task plan, the schedule execution time per executes this Task is initially set, that is, ScheduledExecutionTime (Nth) = firstTexecuteTime n * periodtime; If TASK is executed in the first time, for some reason this time the execution time is too long, the SYSTEMCURRENTTIME> = ScheduledExecutionTime (Nth 1 time) is executed, then do not do the Period interval, immediately perform the N 1 Supreme Task, and the next N 2 times Task ScheduledexecutionTime still is still firstexecutetime (n 2) * Periodtime This will be fixed in the first execution of Task. To put it bluntly, this method pays more attention to the stability of the execution frequency.

5. Some attention issues

Each Timer only corresponds to a unique thread. Timer does not guarantee the very accurate execution of the task. The thread of the Timer class is safe.

转载请注明原文地址:https://www.9cbs.com/read-70087.html

New Post(0)