Reputation: 9
I am using java.util.timer class and i am writing this code
Timer myTimer = new Timer();
MyTask myTask = new MyTask() //MyTask extends TimerTask
Date alarmDate = new Date();
myTimer.schedule(myTask, alarmDate);
and perform multiple task at specific date time by using this method
but i have to stop some of them. How can i do that by method cancel "myTask.cancel(Date date);"?
Upvotes: 1
Views: 653
Reputation: 1831
TimerTask.cancel()
takes no arguments. Just call
myTask.cancel();
Please note the following comment in the API docs for Timer:
Java 5.0 introduced the java.util.concurrent package and one of the concurrency utilities therein is the ScheduledThreadPoolExecutor which is a thread pool for repeatedly executing tasks at a given rate or delay. It is effectively a more versatile replacement for the Timer/TimerTask combination, as it allows multiple service threads, accepts various time units, and doesn't require subclassing TimerTask (just implement Runnable). Configuring ScheduledThreadPoolExecutor with one thread makes it equivalent to Timer.
Although it may be slightly more code to implement, it provides better control over the submitted tasks.
Upvotes: 1