Saturday, 30 April 2011

Java timer test

Example to show java timer:

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

public class TestTimerTask {
public static void main(String[] args) { 
//define a timer 
final Timer timer = new Timer("Test Timer"); 
 
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
System.out.println("Timer fired");
}
}, Calendar.getInstance().getTime(), 5 * 1000);

Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
System.out.println("Canceling timer");
timer.cancel();
}
});
}
}

No comments:

Post a Comment