I'm building a web-app that has its own task scheduling. So far, I have made a task class where you can set the initial start time and the interval between executes. The task object sleeps until its next scheduled run time, then executes, then starts the cycle over again. So my problem is this: These tasks can be modified at any time - so, if the task is modified, and the task is currently sleeping (Thread.sleep()), how can I wake the thread up, modify the values, and start it again? I thought initially I could do some blocking of some sort, but that wouldn't work since I also need it to operate on a timed schedule. I'm thinking I need to throw an exception of some kind, but I can't figure out how to throw an exception from outside the class.... any ideas?
If you have a reference to a sleeping thread, t, you can interrupt it by calling it's interrupt() method, e.g. t.interrupt(); // go figure However, I'm not sure the design you have is ideal. I could be wrong but the design that comes to my mind is for tasks to implement Runnable. Tasks would be defined and queued up, probably in some kind of list. Then you'll have a single monitoring thread, a TaskScheduler, that looks at the task at the head of the queue and then goes to sleep until it's time to kick off that task. The point is, you'll only have one sleeping Thread: the TaskScheduler thread. If the task at the head of the queue is modified, then you would put it back in the queue where it needs to be based on it's schedule/interval, wake up the TaskScheduler by calling its interrupt() method and make it look at the current head-of-the-queue task (which may be the edited one or, if the tasks were reordered, a new one). The TaskScheduler would, if necessary, again go to sleep until the new task needs to be kicked off. I'm sure there are other design considerations but I think that would be the main direction. The advantage to this design would be that task objects don't need to be created until they are really needed and they go away once they are done. With your current design (as I understand it), you could potentially have hundreds or thousands of sleeping threads just lying around waiting to be woken up to get to work.
One cool thing about Timer is that it manages any number of timed tasks on one thread instead of starting a thread for each. Before I got clued into this, I wrote my own scheduler that keeps a collection of scheduled events. It knows what the "next" one is and sleeps until then. Any time you execute, add, change or remove events, it has to go through the collection again to determine the "next". I'm guessing Timer does much the same.
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi