Java TimerTask class

Introduction

We can use TimerTask to schedule events by timer.

The following code defines a timer task whose run() method displays the message "Timer task executed."

This task is scheduled to run once every half second after an initial delay of one second.

// Demonstrate Timer and TimerTask.

import java.util.Timer;
import java.util.TimerTask;

class MyTimerTask extends TimerTask {
  public void run() {
    System.out.println("Timer task executed.");
  }//from www.  ja  va  2  s . c o  m
}

public class Main {
  public static void main(String args[]) {
    MyTimerTask myTask = new MyTimerTask();
    Timer myTimer = new Timer();

    /*
     * Set an initial delay of 1 second, then repeat every half second.
     */
    myTimer.schedule(myTask, 1000, 500);

    try {
      Thread.sleep(5000);
    } catch (InterruptedException exc) {
    }

    myTimer.cancel();
  }
}



PreviousNext

Related