Java Timer.cancel()
Syntax
Timer.cancel() has the following syntax.
public void cancel()
Example
In the following code shows how to use Timer.cancel() method.
import java.util.Timer;
import java.util.TimerTask;
/* w w w .j a v a 2 s.c o m*/
public class Main {
Timer timer;
public Main(int seconds) {
timer = new Timer();
timer.schedule(new RemindTask(), seconds * 1000);
}
class RemindTask extends TimerTask {
public void run() {
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 Main(5);
System.out.println("Task scheduled.");
}
}
The code above generates the following result.
Home »
Java Tutorial »
java.util »
Java Tutorial »
java.util »