Java API Tutorial - Java Timer(String name) Constructor








Syntax

Timer(String name) constructor from Timer has the following syntax.

public Timer(String name)

Example

In the following code shows how to use Timer.Timer(String name) constructor.

import java.util.Timer;
import java.util.TimerTask;
/*from ww w.  ja  v a2 s . c om*/
public class Main {
  Timer timer;

  public Main(int seconds) {
    timer = new Timer("MyTimer");
    timer.schedule(new RemindTask(), seconds * 1000);
  }

  class RemindTask extends TimerTask {
    public void run() {
      System.out.println("Time's up!");
      timer.cancel(); //Terminate the timer thread
    }
  }

  public static void main(String args[]) {
    System.out.println("About to schedule task.");
    new Main(5);
    System.out.println("Task scheduled.");
  }
}

The code above generates the following result.