When a Java TimerTask is scheduled in a Timer, is it already “executing”?

前端 未结 2 867
既然无缘
既然无缘 2021-02-08 02:08

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

timer.schedule(task, 60000);

where the task is scheduled to ru

2条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-08 02:35

    • 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.

提交回复
热议问题