gpt4 book ai didi

java - Java中如何停止计划的任务

转载 作者:太空宇宙 更新时间:2023-11-04 06:45:31 26 4
gpt4 key购买 nike

我正在使用 java.util.timer 类,并且我正在编写这段代码

Timer myTimer = new Timer();
MyTask myTask = new MyTask() //MyTask extends TimerTask
Date alarmDate = new Date();
myTimer.schedule(myTask, alarmDate);

并使用此方法在特定日期时间执行多个任务

但我必须阻止其中一些。我怎样才能通过方法取消“myTask.cancel(Date date);”来做到这一点?

最佳答案

TimerTask.cancel() 不带任何参数。只需调用电话

myTask.cancel();

请注意计时器 API 文档中的以下注释:

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.

尽管实现的代码可能稍微多一些,但它可以更好地控制提交的任务。

关于java - Java中如何停止计划的任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24043108/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com