When Java TimerTask is scheduled in the timer, has it been executed?

I want to clarify about TimerTask When you have the following code:

timer.schedule(task,60000);

The task is scheduled to run in the next 1 minute. Has the task object been executed?

Because somewhere in my code I called task Cancel (), but it seems that this call is not blocked

Task execution I even returned a value from the call record, which returned false

When I read the documentation of the cancellation method, I encountered my problem:

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

Has [task] been executed?

I hope you can give me clues / hints or even explanations thank you!

Solution

>The task is scheduled to run in the next 1 minute, and the task object has been executed

No, it will call the run method of this task within 60 seconds If task Cancel() returns false, which may mean three things:

>The task has been scheduled for one-time execution and has been run or > the task has never been scheduled or > the task has been cancelled or

Therefore, if you decide to call cancellation before 60 seconds after scheduling a task, you may call it multiple times and get the result of subsequent cancellation, or you are calling cancellation in another task

Generally speaking, I suggest timer approve of scheduledexecutorservice

You can achieve the required functions in the following ways:

ScheduledExecutorService. schedule( callable,delay,timeunit )

Reasons why scheduledexecutorservice is a preferred method overview here:

>Timer can be sensitive to the change of system clock. Scheduledthreadpoolexecutor is not > timer. There is only one execution thread, so long-running tasks can delay other tasks Scheduledthreadpoolexecutor can configure any number of threads In addition, you can fully control the threads created. If necessary (by providing threadfactory) > the runtime exception thrown in TimerTask will kill a thread, causing the timer to crash: -... That is, the scheduled task will no longer run. Scheduledthreadexecutor not only captures runtime exceptions, but also allows you to handle them (from ThreadPoolExecutor by overriding the afterexecute method) The task that throws the exception will be canceled, but other tasks will continue to run

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>