views:

39

answers:

1

I have a daemon thread which wakes up at a specified interval to do some task. Now I need to add two more tasks to the thread & these tasks have their own intervals. Something like

  • After every x seconds do Task1
  • After every y seconds do Task2
  • After every z seconds do Task3

So I basically need to come up with a sleep logic to ensure that all the tasks are done at the right time. What would be the most optimal way of doing this? My thought on this was that, the times at which each task is performed is an Arithmetic Progression, so I would need to combine the AP's corresponding to each task & use that series to figure out the time interval I need to sleep as well as the next task to perform. Does this approach make sense?

A: 

You can probably do something like this:

now = time_in_seconds()
time_since_task1 = x - (now % x)
time_since_task2 = y - (now % y)
time_since_task3 = z - (now % z)

shortest_interval = min(min(time_since_task1, time_since_task2), time_since_task3)
sleep(shortest_interval)

Then you can check if the "new now" is equal to 0 mod x,y,z and do the requisite tasks.

Vatine
@Vatine: Could you please explain the logic, not sure I got it. What does time_in_seconds return? Is it the current time in seconds?
Raam
@Raam: Ideally it should be the time elapsed since when the program started - the reference starting point for the tasks.
casablanca
raam: current time in seconds. Possibly with time in seconds at start subtracted (it will make a difference for the first run of each task).
Vatine