advertisement
javaboutique
Search Tips
Articles  |   Tutorials  |   Reviews  |   Tools  |   by Category  |   by Date  |   by Name  |   Submit  |   Source  |   Forums  |  
javaboutique
Browse DevX


Partners & Affiliates











advertisement


Reviews : Java Books :
Beginning Java 2- JDK 1.3 Version : Images and Animation

Buy this book
Title: Beginning Java 2- JDK 1.3 Version
ISBN: 1861003668
US Price: $ 49.99
Canadian Price:
C$ 74.95
UK Price: £ 35.99
Publication Date: March 2000
Pages: 1230
© Wrox Press Limited, US and UK.

Beginning Java 2- JDK 1.3 Version
Images and Animation

You use the scheduleAtFixedRate() method for repeated executions of a task where the precise timing is more important than maintaining the interval between successive executions. This is referred to as fixed-rate execution. Each execution is scheduled relative to the first execution of the task, not the preceding one. If you wanted to simulate a clock for instance using Timer and TimerTask objects you would use the scheduleAtFixedRate() method to schedule updating the position of the hands on the clock rather than the schedule() method because you want the hand positions to be set as close as possible to absolute time. If any execution of the update to the hand position is delayed for any reason, succeeding executions will 'bunch-up' in time in order to try to maintain their schedule in real time.

image5-2

This is shown graphically in the diagram, which contrasts the two types of scheduling operations you can use.

You have two versions of the scheduleAtFixedRate() method available to you, both of which are for scheduling a task repeatedly:

scheduleAtFixedRate
         TimerTask task,
            Date    firstTime,
            long    period)

This schedules the task determined by the first argument, task, to be executed repeatedly starting at the time specified by the second argument, firstTime. The third argument, period, specifies the period in milliseconds between the start time of one execution of the task and the start time of the next. If the current time is later than the time specified for the first execution of the task, then the task executes immediately.

scheduleAtFixedRate(
         TimerTask task,
            long    delay,
            long    period)

This schedules the task determined by the first argument, task, to be executed repeatedly with the first execution starting after a delay relative to the current time of delay milliseconds. The third argument, period, specifies the period in milliseconds between the start time of one execution of the task and the start time of the next.

Both the schedule() and scheduleAtFixedRate() methods can throw exceptions. An exception of type IllegalArgumentException will be thrown if a delay argument is negative or if an argument of type Date represents a negative time value (as returned by its getTime() method). An exception of type IllegalStateException will be thrown if the task was already scheduled or if the task or the timer was cancelled.

Let's turn to how we use the TimerTask class to define a task to be scheduled by a Timer object.

TimerTask Objects

TimerTask is an abstract class, so you will need to derive your own class from it. The class implements the Runnable interface so a TimerTask object defines a thread. The run() method in the TimerTask class is abstract because it is this method that specifies the task to be executed and it's your job to decide this. Of course, you can define your class with TimerTask as a base in its own source file, but more often than not you will want to define it by an anonymous class. The form of the code for scheduling such a task will be something like this:

TimerTask task = new TimerTask()
            {
              public void run()
              {
               // Code defining the task to be executed.
              }
            }

To schedule the task that this creates for repeated execution at one second intervals starting five seconds from now we could write:

Timer timer = new Timer(true); // Create a timer with a daemon thread 
timer.scheduleAtFixedRate(task, new Date(System.currentTimeMillis()+5000), 1000);

The currentTimeMillis() method returns the current time from the system clock in milliseconds. We add 5000 milliseconds to this to specify the instant five seconds from now. Since we call the scheduleAtFixedRate() method here to schedule the task, the fixed-delay execution method will apply.

The TimerTask class contains just one other method besides the run() method – the cancel() method, which you call to cancel the execution of a task. Calling the cancel() method for a given TimerTask object permanently stops execution of that task, whether it has been scheduled for one-time execution or repeated execution. For example:

task.cancel(); // Terminate the task

The task will be terminated and cannot be run again. If you want to run the task again you need to create a new TimerTask object and schedule that for execution. If a task has been canceled previously, calling cancel() again will have no effect. The cancel() method for a TimerTask object provides you with control at a task level. As we said earlier, you can use a Timer object to schedule several different tasks, each of which will be defined by an object that has TimerTask as a superclass. Calling the cancel() method for an individual task will terminate the execution of that task without affecting any others.

When you want to terminate all the tasks currently managed by a Timer object you just call the cancel() method for the Timer object. For instance:

timer.cancel(); // Terminate the timer

This terminates all tasks scheduled by timer, and also terminates the Timer object's thread so it cannot be used again.

Let's rewrite the previous WhirlingLogo example to use a Timer object.

How to Add Java Applets to Your Site

New on the Java Boutique:

New Review:

Time Management Made Easy with the Quartz Enterprise Job Scheduler
Why not just use the Java timer API? This open source scheduling API boasts simplicity, ease-of-integration, a well-rounded feature set, and it's free!

New Applet:

Reverse Complement
Reverse Complement is a simple applet that converts DNA or RNA sequences into three useful formats.

Elsewhere on internet.com:

WebDeveloper Java
Lots of Java information on webdeveloper.com

WDVL Java
Thorough Java resource at the Web Developer's Virtual Library.

ScriptSearch Java
Hundreds of free Java code files to download.

jGuru: Your View of the Java Universe
Customizable portal with online training, FAQs, regular news updates, and tutorials.

XML error: undefined entity at line 19
advertisement
Receive Articles via our XML/RSS feed
Receive Articles via our XML/RSS feed

JavaBytes
Internet Cyclone
This powerful, easy-to-use, internet optimizer is for Windows 95, 98, ME, NT, 2000 and XP. It's designed to automatically optimize your Windows settings, boosting your Internet connection up to 200%.

Linux Vendors Head to the Cloud in Search of Cash
iPhone 3GS: Overheating Fears, OS Update Nears
PostgreSQL 8.4 Revs Up Database Admin, Security
PHP 5.3 Accelerates PHP
Sun Releases NetBeans 6.7 IDE for Java, PHP
Why Firefox Doesn't Take Google Chrome Features
First Major PHP Update in Years Coming Soon
Red Hat CEO Calls on Oracle to Keep Java Open
Google Widens AdSense for iPhone, Android Apps
Eclipse Galileo Releases 33 Open Source Projects

A Taste of JavaFX for the Uninitiated
A Guide to Caching and Compression for High Performance Web Applications
How User-Centered Design Can Put User Stories in Proper Context
Explore C# 4's New Dynamic Types and Named/Optional Parameters
Enterprise Architecture: The Journey Begins Here, Part 2
Create a Syslog Sender/Receiver Using the MS Winsock Control
AMD CodeAnalyst Helps Developers Optimize and Tune Applications
Securing Microsoft's Cloud Infrastructure
Introducing the Azure Services Platform
An Introduction to Microsoft .NET Services for Developers

Advertising Info  |   Member Services  |   Contact Us  |   Help  |   Feedback  |   Site Map  |   Network Map  |   About

internet.commediabistro.comJusttechjobs.comGraphics.com

Search:

WebMediaBrands Corporate Info

Legal Notices, Licensing, Reprints, Permissions, Privacy Policy.
Advertise | Newsletters | Shopping | E-mail Offers | Freelance Jobs