views:

75

answers:

1

Hi,

I have a task that needs to be executed on a schedule. (It basically polls a database looking for a change and then executes code depending on the result). The problem is that I need the polled task to happen even when it is already executing.

So far I have tried using a Timer/TimerTask combo with the scheduleAtFixedRate() method and the ScheduledThreadPoolExecutor/Thread combo with the scheduleAtFixedRate() method.

Both wait for the current scheduled task to complete before running the next. I need to be able to schedule a task to run every 5 seconds and have it run even if the last execution of the task has not yet completed.

Any ideas?

+2  A: 

How about using one Timer as the "kick-off" timer, but then a separate thread pool for execution: when the timer ticks, you submit the task to the thread pool for immediate execution. (You may want to tweak the thread pool to have some maximum number of tasks running simultaneously.)

Jon Skeet
That is working but if one of the threads from the pool generates an exception (even if I catch it) it appears to cancel the "kick-off" timer and prevents it polling.
Tom
@Tom: That seems very unlikely, given that it will be on a different thread by that time. If you could provide a short but complete program which demonstrates the problem, that would help.
Jon Skeet
@Jon: I just realised what was causing the problem. It was actually that I was not removing that thread from my list of active threads when an exception was raised which gave the appearance that it has hung. Thanks for your help! :)
Tom
@Tom: Glad it all worked out in the end :)
Jon Skeet