Java Reference
In-Depth Information
For periodic events, if the duration of processing in between the sleep periods
varies significantly, then the overall timing will vary with respect to a clock. Also,
if you need several timer events, the program will require several threads and this
will use up system resources.
Java provides two timer classes [5-7]:
javax.swing.Timer
came with the Swing packages and is useful for such tasks as
prompting the updating of a progress bar
java.util.Timer
and its helper class
java.util.TimerTask
provide for general
purpose timers with more features than the Swing timer
These timers can provide multiple timed events from a single thread and thus
conserve resources. They also have useful methods such as
scheduleAt-
FixedRate(TimerTask task, long delay, long period)
in
java.
util.Timer
. This method will set events to occur periodically at a fixed rate
and ties them to the system clock. This is obviously useful for many applications
such as a countdown timer and an alarm clock where you don't want the timing
to drift relative to absolute time.
8.7.1
java.util.Timer
and
TimerTask
The
Timer
and
TimerTask
combo in
java.util
offers the most general
purpose timing capabilities and includes a number of options. A
Timer
object
holds a single thread and can control many
TimerTask
objects. The
TimerTask
abstract class implements the
Runnable
interface but it does not provide a
concrete
run()
method. Instead you create a
TimerTask
subclass to provide
the concrete
run()
method with the code to carry out the task of interest.
In the example below, we create a digital clock using a timer to redraw a
time display every second. The clock display uses
DateFormatPanel
,which
we describe in Chapter 10 when discussing the date classes. Whenever this
panel is drawn it displays the current time. The applet adds an instance of this
panel to its content pane and in the
start()
method creates an instance of
java.util.Timer
.
A subclass of
TimerTask
called
UpdateTask
overrides the
run()
method
and simply tells the panel to redraw itself.
UpdateTask
is defined as an inner
class here and has access to the clock panel reference. The timer schedules
calls to the
UpdateTask
every 1000 milliseconds. Figure 8.9 shows the clock
display.
Figure 8.9
The
ClockTimer1
and
ClockTimer2
programs,
which both provide a
current time display like
that shown here, illustrate
the use of
java.util.Timer
and
javax.swing.Timer
,
respectively.
import javax.swing.*;
import java.awt.*;
import java.util.*;
/** This applet implements Runnable and uses a thread
Search WWH ::
Custom Search