views:

69

answers:

2

I am building an application which needs to call a certain API at specific times. I would like to set execution times for each of the calls, and have my execute function be called automatically when each call needs to execute. What's the best way to do this?

I have thought about creating a new Timer for each new call that needs to be executed, with the timer's only interval being set to its execution time. Is this a good way of achieving what I need or is there something more efficient?

+2  A: 

That's a reasonable approach for a small number of timers/threads. For a large number, you'd use one timer set to the greatest common denominator of the intervals and have it select the appropriate task (if any) to launch.

Using a Windows Scheduled Task is almost certainly overkill.

EricLaw -MSFT-
I agree with the single timer that dispatches tasks. If you need to launch at a specific time, such as the top of the minute, then your timer interval will need to be small enough to detect the minute change within your resolution requirement (such as within one second).
ebpower
A: 

I like to use a single thread (or threadpool thread) with a ResetEvent (manual or Auto) with a timeout set to some fraction of the fastest task (say once ever 5 seconds). Externally you can call the event to process the pending dispatches, or every time it timeouts you can also check for pending dispatches.

If you set the timeout to a fraction (say 30%) of the smallest interval then you can keep decent control over how much time your "check" process takes, but if you miss an interval you have a reasonable period of time in which to dispatch the task. It also gives you your window of reasonable launch.

Implementation can be done by maintaining a ordered list of which api call needs to happen next and setting the timeout to some fraction of that.

GrayWizardx
... or a minheap of times :-) Heaps don't come up that much; I think I've even used Ternary Trees more.
Robert Fraser
Haha! Good point. There are definitely alternatives to the order list.
GrayWizardx