Create a timer task in Java
Description
The following code shows how to create a timer task.
The java.util.Timer class provides an alternative way to perform scheduled or recurrent tasks.
Example
//from w ww .ja v a 2 s . c o m
import java.util.Timer;
import java.util.TimerTask;
public class Main {
public static void main(String[] args) {
Timer timer = new Timer();
timer.schedule(new DisplayQuestionTask(), 0, 10 * 1000);
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
}
timer.cancel();
}
}
class DisplayQuestionTask extends TimerTask {
int counter = 0;
public void run() {
System.out.println(counter++);
}
}
The code above generates the following result.