如何重新启动TimerTask [英] How to relaunch a TimerTask
问题描述
我编写了一个通过套接字发送某条TCP消息的任务。我有一个包含大量消息和一些时间戳的文件,因此我将任务编程为TimerTask,并使用带有第一个消息时间戳的Timer安排它。
I have written a task to send a certain TCP message through a socket. I have a file with a bunch of messages and some timestamps, so I programmed the task as a TimerTask, and I scheduled it with a Timer with the first message timestamp.
完成后,任务运行方法结束,但其关联的线程仍然存在,它不会被取消。如果我尝试用新的时间重新安排任务,我会得到一个例外,告诉我我不能重新安排一个调整或取消的任务。
When it finishes, the task run method is over, but its associated thread remains, it's not cancelled. If I try to reschedule the task with a new Time, I'm getting an exception telling me that I cannot reschedulle a schedulled or cancelled task.
我也试过取消它在重新安排之前,但显然,正如例外所述,它仍然是同样的问题。
I also tried cancellig it before rescheduling, but obviously, as the exception told, it remains the same problem.
我不能用一个常数perior安排任务让它重复自己,因为每条消息都有一个时间且它不是常数。
I can't schedule the task with a constant perior to let it repeat itself, because each message has a time and it is not constant.
如何重新安排TimerTask?顺便说一下,有没有办法等待任务结束,就像套接字通信中的阻塞一样,直到消息到达为止?
How can I reschedule the TimerTask? And by the way, is there any way of waiting for the task to end, just as in socket communications when it blocks with ready method until a message arrives?
推荐答案
TimerTask不是为了重新安排而设计的,它是管理(单个)线程的Timer。
A TimerTask is not designed to be rescheduled and it is the Timer that manages the (single) thread.
使用 one 计时器和许多 new
TimerTasks:
Use one Timer and many new
TimerTasks:
对应每个Timer对象是单个后台线程用于执行所有计时器的任务,顺序执行..
Corresponding to each Timer object is a single background thread that is used to execute all of the timer's tasks, sequentially ..
最后一次对Timer对象的实时引用消失后所有未完成的任务都已完成执行,计时器的任务执行线程[应该]正常终止(并成为垃圾收集)。
After the last live reference to a Timer object goes away and all outstanding tasks have completed execution, the timer's task execution thread [should] terminates gracefully (and becomes subject to garbage collection).
[来自每个 schedule 方法:]
[From each of the schedule methods:]
如果[TimerTask]已经安排或取消,计时器被取消或计时器线程终止,则抛出IllegalStateException。
Throws IllegalStateException if [the TimerTask] was already scheduled or cancelled, timer was cancelled, or timer thread terminated.
如果确实有多个线程由一个Timer产生,那么将成为一个不太可能发生的错误:确保实际上只有一个Timer对象存在使用。
If there are indeed many threads spawned by a single Timer, then that would be a bug which is unlikely: make sure there really is only one Timer object being used.
关于如何将单个事件组合到工作流程中的最后一个问题应该是一个单独的帖子。
The last question, of how to compose individual events into a workflow, should be a separate post.
这篇关于如何重新启动TimerTask的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!