How To Fix Java Timer Not Following Delay
Start of Tutorial > First of Trail > Start of Lesson | Search Feedback Class |
Trail: Essential Java Classes
Lesson: Threads: Doing Two or More Tasks At Once
Using the Timer and TimerTask Classes
This department discusses practical aspects of using timers to schedule tasks. TheTimer
class in thecoffee.util
package schedules instances of a grade chosenTimerTask
.is an example of using a timer to perform a task after a filibuster:
Reminder.coffee
import java.util.Timer; import java.util.TimerTask; /** * Simple demo that uses coffee.util.Timer to schedule a task * to execute in one case five seconds have passed. */ public course Reminder { Timer timer; public Reminder(int seconds) { timer = new Timer(); timer.schedule(new RemindTask(), seconds*1000); } form RemindTask extends TimerTask { public void run() { System.out.println("Time's upwardly!"); timer.cancel(); //Terminate the timer thread } } public static void main(String args[]) { new Reminder(5); System.out.println("Task scheduled."); } }When you run the example, you get-go see this:
Job scheduled.5 seconds later, you see this:
Fourth dimension's up!This elementary plan illustrates the bones parts of implementing and scheduling a chore to be executed by a timer thread.
- Implement a custom subclass of
TimerTask
. Therun
method contains the lawmaking that performs the job. In this example, the subclass is namedRemindTask
.
- Create a thread by instantiating the
Timer
class.
- Instantiate the timer task object (
new RemindTask()
).
- Schedule the timer chore for execution. This example uses the
schedule
method, with the timer task as the starting time statement and the delay in milliseconds (5000
) as the second argument. Another fashion of scheduling a task is to specify the fourth dimension when the task should execute. For example, the post-obit lawmaking schedules a task for execution at eleven:01 p.1000.://Get the Date respective to eleven:01:00 pm today. Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.HOUR_OF_DAY, 23); agenda.set(Calendar.Minute, 1); calendar.set up(Agenda.2d, 0); Date fourth dimension = agenda.getTime(); timer = new Timer(); timer.schedule(new RemindTask(), time);
Stopping Timer Threads
By default, a program keeps running as long as its timer threads are running. Yous can end a timer thread in four ways.The
- Invoke
cancel
on the timer. You can do this from anywhere in the programme, such as from a timer chore'srun
method.- Brand the timer's thread a "daemon" by creating the timer like this:
new Timer(true)
. If the only threads left in the programme are daemon threads, the program exits.- After all the timer's scheduled tasks have finished executing, remove all references to the
Timer
object. Eventually, the timer'southward thread will terminate.- Invoke the
System.go out
method, which makes the entire plan (and all its threads) exit.Reminder
case uses the first scheme, invoking the cancel method from the timer task'srun
method. Making the timer thread a daemon wouldn't piece of work, because the program needs to go on running until the timer'south task executes.Sometimes, timer threads aren't the only threads that tin can foreclose a programme from exiting when expected. For example, if you use the AWT at all — even if merely to brand beeps — the AWT automatically creates a nondaemon thread that keeps the program live. The following modification of
Reminder
adds beeping, which requires us to as well add together a phone call to theOrganisation.go out
method to brand the program exit. Significant changes are in highlighted. You can find the source code in.
ReminderBeep.java
public class ReminderBeep { ... public ReminderBeep(int seconds) { toolkit = Toolkit.getDefaultToolkit(); timer = new Timer(); timer.schedule(new RemindTask(), seconds*chiliad); } grade RemindTask extends TimerTask { public void run() { System.out.println("Time'due south up!"); toolkit.beep(); //timer.cancel(); // Non necessary considering // we telephone call Organisation.get out System.get out(0); // Stops the AWT thread // (and everything else) } } ... }
Performing a Chore Repeatedly
Here�southward an example of using a timer to perform a task once per second.You tin can detect the entire programme inpublic 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 telephone call Organization.go out System.go out(0); // Stops the AWT thread // (and everything else) } } } ... }. When y'all execute it, you see the following output (our comments about timing are shown in italics):
AnnoyingBeep.java
TheTask scheduled. Beep! Beep! //one 2nd subsequently the first beep Beep! //one second afterward the 2d beep Fourth dimension's upwards! //one second after the third beepAnnoyingBeep
program uses a three-statement version of theschedule
method to specify that its task should execute once a second, beginning immediately. Here are all theTimer
methods you lot can use to schedule repeated executions of tasks:
schedule(TimerTask task, long delay, long period)
schedule(TimerTask job, Date fourth dimension, long menstruum)
scheduleAtFixedRate(TimerTask task, long filibuster, long period)
scheduleAtFixedRate(TimerTask chore, Date firstTime, long period)
When scheduling a task for repeated execution, you should utilize i of the
schedule
methods when smoothness is important and ascheduleAtFixedRate
method when fourth dimension synchronization is more than important. For example, theAnnoyingBeep
programme uses theschedule
method, which means that the annoying beeps will all be at least 1 2d autonomously. If one beep is late for any reason, all subsequent beeps will be delayed. If we decide that theAnnoyingBeep
program should go out exactly 3 seconds after the kickoff beep — even if information technology means that two beeps might occur close together if a beep is delayed for whatever reason — nosotros should utilise thescheduleAtFixedRate
method instead.More Information about Timers
The timer tasks we've shown have been very simple. They do near nothing and refer just to data that either tin can exist safely accessed from multiple threads or is private to the timer task. As long as your timer task uses only API designed to be thread-safe — such as the methods in the
Timer
form — implementing timers is relatively straightforward. Nevertheless, if your timer implementation depends on shared resources, such as information used by other places in your program, you demand to be careful. Yous tin find out more than subsequently in this chapter in the section Synchronizing Threads.
Outset of Tutorial > Starting time of Trail > Get-go of Lesson | Search Feedback Grade |
Copyright 1995-2005 Dominicus Microsystems, Inc. All rights reserved.
How To Fix Java Timer Not Following Delay,
Source: https://www.iitk.ac.in/esc101/05Aug/tutorial/essential/threads/timer.html
Posted by: bergergaceaddly.blogspot.com
0 Response to "How To Fix Java Timer Not Following Delay"
Post a Comment