Share this page 

Create a Timer objectTag(s): Thread


JDK 1.3 (or better) provides new classes called java.util.Timer and java.util.TimerTask.
import java.util.Timer;
import java.util.TimerTask;

public class ToDo  {
  Timer timer;

  public ToDo ( int seconds )   {
    timer = new Timer (  ) ;
    timer.schedule ( new ToDoTask (  ) , seconds*1000 ) ;
  }


  class ToDoTask extends TimerTask  {
    public void run (  )   {
      System.out.println ( "OK, It's time to do something!" ) ;
      timer.cancel (  ) ; //Terminate the thread
    }
  }


  public static void main ( String args [  ]  )   {
    System.out.println ( "Schedule something to do in 5 seconds." ) ;
    new ToDo ( 5 ) ;
    System.out.println ( "Waiting." ) ;
  }
}

Swing also provide a Timer class. A Timer object will send an ActionEvent to the registered ActionListener.

import javax.swing.Timer;
import java.awt.event.*;
import java.util.*;

public class TimerDemo implements ActionListener {
  Timer t = new Timer(1000,this);

  TimerDemo() {
    t.start();
    }

  public static void main(String args[]) {
    TimerDemo td = new TimerDemo();
    // create a dummy frame to keep the JVM running
    //  (for demonstation purpose)
    java.awt.Frame dummy = new java.awt.Frame();
    dummy.setVisible(true);
    }

  public void actionPerformed(ActionEvent e) {
    if (e.getSource() == t) {
      System.out.println 
        ("\007Being ticked " + Calendar.getInstance().getTime());
      }
    }
}