当 Java TimerTask 在 Timer 中调度时,它是否已经“执行”了?

发布于 2024-12-15 02:47:03 字数 520 浏览 3 评论 0原文

我想澄清一些关于 TimerTask 的事情。当您有以下代码时:

timer.schedule(task, 60000);

任务计划在接下来的 1 分钟内运行,任务对象是否已经在执行?

因为在我的代码中的某个地方我调用了task.cancel(),但似乎该调用并没有阻止

任务的执行。我什至记录了调用的返回值,它返回 false。

当我阅读取消方法的文档时,我提出了我的问题:

取消 TimerTask 并将其从计时器队列中删除。 通常,如果调用没有阻止 TimerTask,则返回 false 至少运行一次。后续调用没有任何效果。如果调用阻止了计划执行的发生,则返回 true,否则返回 false。

我相信我在 1 分钟延迟之前调用了 cancel() 。但是cancel怎么返回false呢,

难道[task]已经在执行了?

希望您能给我线索/提示,甚至对此进行解释。谢谢!

I would like to clarify something about TimerTask. When you have the code below:

timer.schedule(task, 60000);

where the task is scheduled to run in the next 1 minute, is the task object already executing?

because somewhere in my code I called task.cancel() but it seems that the call doesn't prevent

task to be executed. I even logged the return value from the call and it returns false.

I came about my question when I read the documentation for the cancel method:

Cancels the TimerTask and removes it from the Timer's queue.
Generally, it returns false if the call did not prevent a TimerTask
from running at least once. Subsequent calls have no effect. Returns true if the call prevented a scheduled execution from taking place, false otherwise.

I believe I called cancel() before the 1 minute delay. But how come cancel returned false,

is it [task] already executing?

Hope you can give me clues/hints or even an explanation to this. Thanks SO!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

一个人的旅程 2024-12-22 02:47:03
  • 任务计划在接下来的 1 分钟内运行,任务对象是否已经在执行

否,它将调用 run 方法在 60 秒内完成此任务。如果 task.cancel() 返回 false,这可能意味着 3 件事:

  • 任务被安排为一次性执行并且已经运行,或者
  • 从未被安排,或者
  • 任务 任务已被取消,或者

因此,如果您确定在安排任务后 60 秒之前调用 cancel,您可能会多次调用它,并从后续的 cancel 中获取结果,或者您正在对不同的任务调用取消。


一般来说,我建议不要使用 Timer支持 ScheduledExecutorService

你可以实现所需的功能:

ScheduledExecutorService.schedule( callable, delay, timeunit )

原因ScheduledExecutorService 是一种首选方式,此处概述:

  • 计时器可以是对系统时钟的变化敏感,ScheduledThreadPoolExecutor 则不敏感

  • Timer 只有一个执行线程,因此长时间运行的任务可能会延迟其他任务。 ScheduledThreadPoolExecutor 可以配置任意数量的线程。此外,如果您愿意,您可以完全控制创建的线程(通过提供 ThreadFactory)

  • TimerTask 中抛出的运行时异常会杀死该线程,从而使 Timer 死亡:-( ...即计划任务将不再运行。ScheduledThreadExecutor不仅捕获运行时异常,还可以让您根据需要处理它们(通过重写 ThreadPoolExecutor 的 afterExecute 方法)。抛出异常的任务将被取消,但其他任务将继续执行。运行。

  • where the task is scheduled to run in the next 1 minute, is the task object already executing

No, it is going to invoke the run method of this task in exactly 60 seconds. If task.cancel() returns false, that could mean 3 things:

  • the task was scheduled for one-time execution and has already run OR
  • the task was never scheduled OR
  • the task was already cancelled OR

Hence, if you are certain that you call cancel before 60 seconds after scheduling the task, you could potentially either call it several times, and get a result from a subsequent cancel, OR you are calling cancel on a different task.


In general, I would recommend against Timer in favor of a ScheduledExecutorService

You can achieve a desired functionality with:

ScheduledExecutorService.schedule( callable, delay, timeunit )

Reasons why ScheduledExecutorService are is a preferred way are outlined here:

  • Timer can be sensitive to changes in the system clock, ScheduledThreadPoolExecutor isn't

  • Timer has only one execution thread, so long-running task can delay other tasks. ScheduledThreadPoolExecutor can be configured with any number of threads. Furthermore, you have full control over created threads, if you want (by providing ThreadFactory)

  • runtime exceptions thrown in TimerTask kill that one thread, thus making Timer dead :-( ... i.e. scheduled tasks will not run anymore. ScheduledThreadExecutor not only catches runtime exceptions, but it lets you handle them if you want (by overriding afterExecute method from ThreadPoolExecutor). Task which threw exception will be canceled, but other tasks will continue to run.

北恋 2024-12-22 02:47:03

我不知道为什么你的代码返回false

以下代码打印 true

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


public class Test {
    public static void main(String[] args) {
        Timer timer = new Timer();
        TimerTask task = new TimerTask() {

            @Override
            public void run() {
                System.out.println("hi");
            }

        };
        timer.schedule(task, 60000);
        System.out.println(task.cancel());
    }
}

如果最后一个 println 被注释,程序将打印 hi

I don't know why your code returns false.

The following code prints true.

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


public class Test {
    public static void main(String[] args) {
        Timer timer = new Timer();
        TimerTask task = new TimerTask() {

            @Override
            public void run() {
                System.out.println("hi");
            }

        };
        timer.schedule(task, 60000);
        System.out.println(task.cancel());
    }
}

If the last println is commented, the program prints hi.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文