How to relaunch a TimerTask

2019-03-01 12:41发布

问题:

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.

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.

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?

回答1:

A TimerTask is not designed to be rescheduled and it is the Timer that manages the (single) thread.

Use one Timer and many new TimerTasks:

Corresponding to each Timer object is a single background thread that is used to execute all of the timer's tasks, sequentially ..

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

[From each of the schedule methods:]

Throws IllegalStateException if [the TimerTask] was already scheduled or cancelled, timer was cancelled, or timer thread terminated.

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.