Timers in Java

To run a timer in Java application you need two objects: timer and task. When implementing a timer, you need three basic methods: startTimer(), stopTimer() and isTimerRunning().

The task class must extend TimerTask class and override the run() method. run() method is executed when timer expires.

In startTimer() method you need to instance new java.util.Timer object and your implementation of task (ExampleTimerTask) object. To start a timer assign the task to a timer with schedule(..) method.

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

public class Reminder {

public Timer timer;

public ExampleTimerTask exampleTask;


public Reminder() {
}


public void startTimer(int sec) {

// before running timer, check if it is stopped
stopTimer();

// create new timer and timer task
timer = new Timer();
exampleTask = new ExampleTimerTask();

// start timer and run the remindTask at expiration
timer.schedule(exampleTask, sec*1000);
}


public void stopTimer() {

if (timer != null) {
timer.cancel();
timer = null;
}

if (exampleTask != null) {
exampleTask.cancel();
exampleTask = null;
}
}

public boolean isTimerRunning() {

if (timer != null || exampleTask != null) {
return true;
} else {
return false;
}
}


// you can also make this in separate class
public class ExampleTimerTask extends TimerTask {
public void run() {
System.out.println("Time's up!");
// some code to be executed
}
}

public static void main(String args[]) {

Reminder r = new Reminder();
r.startTimer(10);
r.stopTimer();
r.startTimer(3);
if (r.isTimerRunning()) {
System.out.println("Timer is running...");
}
}
}