简体   繁体   English

将线程启动延迟到特定时间的最佳方法是什么?

[英]What is the best way to delay thread starts until a specific time?

I am building an application which needs to call a certain API at specific times.我正在构建一个需要在特定时间调用某个 API 的应用程序。 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?这是实现我需要的好方法还是有更有效的方法?

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.使用 Windows 计划任务几乎肯定是矫枉过正。

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).我喜欢使用带有 ResetEvent(手动或自动)的单个线程(或线程池线程),并将超时设置为最快任务的一小部分(例如每 5 秒一次)。 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.如果您将超时设置为最小间隔的一小部分(比如 30%),那么您可以很好地控制“检查”过程花费的时间,但是如果您错过了一个间隔,您有合理的时间段分派任务。 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.实现可以通过维护一个有序列表来完成,其中列出接下来需要发生的 api 调用并将超时设置为其中的一部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM