A Java TimerTask, Timer, and scheduleAtFixedRate example

As a quick note, if you ever need to use a Java TimerTask, you can define one like this:

class BrightnessTimerTask extends TimerTask {
    @Override
    public void run() {
        // your custom code here ...
    }        
}

and you can then instantiate it, create a Timer, and schedule the task like this:

// run this task as a background/daemon thread
TimerTask timerTask = new BrightnessTimerTask();
Timer timer = new Timer(true);
timer.scheduleAtFixedRate(timerTask, 0, 5*60*1000);

That last line of code runs the task every five minutes with a zero-second delay time, but you can also schedule a task to be run just once. See the Javadoc for the schedule method.

A real Java TimerTask example

As an example of some real TimerTask code, I’m currently using this code in an application I’m working on:

class BrightnessTimerTask extends TimerTask {
    @Override
    public void run() {
        //JOptionPane.showMessageDialog(null, "Entered TimerTask::run()");
        if (originalImage != null) {
            SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                FadingImagePanel fip = new FadingImagePanel(originalImageScaled, newImage, 50, 3000);
                getContentPane().removeAll();
                getContentPane().add(fip, BorderLayout.CENTER);
                getContentPane().validate();
            }});
        }
    }        
}

The actual code inside the run method isn’t important, I just wanted to share a more complete example.

This is a just a quick note on how to use the Java TimerTask and Timer; for more details, see the Java TimerTask Javadoc.