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 开发者_StackOverflow中文版achieving what I need or is there something more efficient?
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.
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.
精彩评论