简体   繁体   中英

How to stop the task scheduled in Java

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);"?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM