Tuesday, August 10, 2010

Java's Thread Timer

A thread timer can be used with Java; See the program below with Java utilities. 

[+/-] show/hide

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

* Simple demo that uses java.util.Timer to schedule a task to execute once 5
* seconds have passed.

public class ThreadReminder {
Timer timer;

public ThreadReminder(int seconds) {
timer = new Timer();
timer.schedule(new RemindTask(), seconds * 1000);

class RemindTask extends TimerTask {
public void run() {

int x=1;
for(int ctr=1000;ctr<=1005;ctr++)
System.out.print(" "+x++); 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 ThreadReminder(5);
System.out.println("Task scheduled."); } }