Scheduling a recurring event (Timers)

So you need an event to occur at regular intervals without doing your own time checks and forcing your application to operate sequentially? You have a number of options open to you but my favourites are the Timer classes, either javax.swing.Timer or java.util.Timer.

Both classes will do what you need and are very similar in functionality but java.util.Timer has loads more options and does not run in the GUI event thread. A good reason for using javax.swing.Timer is that its usage is based on the GUI event dispatch model and so very familiar for Swing developers. If you are using your timer for controlling GUI events then the Swing version maybe your way to go.

java.swing.Timer example:
  // Create a repeating timer event
  javax.swing.Timer t = new javax.swing.Timer(1000, new ActionListener() {
      public void actionPerformed(ActionEvent e) {
            System.out.println("this prints every second");
      }
  }

// to start the timer
t.start();

If you are working on a multi-threaded application, need more timers, or your called method will cause a user-perceived delay (other GUI update events will be blocked) then this Timer may not be for you. Your other option is the equally usable java.util.Timer and my preferred choice 🙂

  ....some method in your class
      // Create a new timer task scheduled to repeat every second
      java.util.Timer timer = new java.util.Timer()
      timer.schedule(new ttask(), 1000, 1000);
  ....end of your method

  // Create an innerclass for your timertask. This is called by your timer
  class ttask extends java.util.TimerTask {
      public void run() {
            System.out.println("this prints every second");
      }
  }

  .....inside another method
      // to stop your timer call
      timer.cancel();

That’s Java timers in a nutshell. Pretty easy once you know how.

About Warren Cross

A contract IT professional that has been in the technology industry a number of years at various blue chip companies. During his career he has been a successful application developer, analyst, project manager, IT manager and system administrator, and performed in both global and local roles. For contract opportunities feel free to contact Warren through this site.
This entry was posted in Java, learning by example and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *