Delphi Clinic C++Builder Gate Training & Consultancy Delphi Notes Weblog Dr.Bob's Webshop
Hubert Klein Ikkink (aka Mr.Haki) - Communications Officer
 Mr.Haki's JBuilder Jar #15
See Also: JBuilder Papers

It is that time(r) again!
The borland.jbcl.util package contains a lot of useful classes, but isn't documented very well. One of those utility classes is the Timer class. We can use this class to start and stop timers in our applications. Let's take a look at the Timer class and use it in a simple example application.

Available methods
The Timer class contains two static public methods:

The startTimer is used for starting the timer. This methods takes four parameters:

  1. borland.jbcl.util.TimerClient client, this is a interface. This interface contains one method, timerEvent(int id). Every time the Timer has passed its waiting period it fires a timer event, and the timerEvent() method will be invoked. Every class which wants to respond to the timer events needs to implement this interface. In the implementation of the timerEvent() method we can write our code we want to be executed.
  2. int eventId, this parameter identifies a certain timer. We can invoke the startTimer() method with different event IDs.
  3. long delay, the delay of the timer in milliseconds.
  4. boolean repeat, should the timer only run once or should it be repeated?

The stopTimer() method stops the timer. The two parameters are the same as the first two parameters for the startTimer() method.

Example
The following example application uses two timers, who have delays of 1000 milliseconds and 600 milliseconds. The first timer will be repeated, and the second timer will not be repeated. When the timer event is fired the application will print a single line to the output.

  package com.drbob42.jbjar.tip14;

  import borland.jbcl.util.Timer;
  import borland.jbcl.util.TimerClient;

  public class TimerExample implements TimerClient {
    private static final int TIMER1 = 0;
    private static final int TIMER2 = 1;

    private static final long DELAY1 = 1000;
    private static final long DELAY2 =  600;

    public TimerExample() {
      Timer.startTimer(this, TIMER1, DELAY1, true);
      Timer.startTimer(this, TIMER2, DELAY2, false);
    }

    public static void main(String[] args) {
      TimerExample timerExample = new TimerExample();
    }

    public void timerEvent(int id) {
      switch (id) {
        case TIMER1:
          System.out.println("Timer 1 - This will be repeated every second");
          break;
        case TIMER2:
          System.out.println("Timer 2 - Only one time");
          break;
        default:
          break;
      }
    }
  }


This webpage © 1997-2009 by Bob Swart (aka Dr.Bob - www.drbob42.com). All Rights Reserved.