将线程启动延迟到特定时间的最佳方法是什么?
我正在构建一个需要在特定时间调用特定 API 的应用程序。我想为每个调用设置执行时间,并在每个调用需要执行时自动调用我的执行函数。最好的方法是什么?
我考虑过为每个需要执行的新调用创建一个新的计时器,并将计时器的唯一间隔设置为其执行时间。这是实现我需要的好方法还是有更有效的方法?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对于少量计时器/线程来说,这是一种合理的方法。对于大量任务,您可以使用一个计时器,将其设置为间隔的最大公分母,并让它选择要启动的适当任务(如果有)。
使用 Windows 计划任务几乎肯定是矫枉过正。
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.
我喜欢将单个线程(或线程池线程)与 ResetEvent(手动或自动)一起使用,并将超时设置为最快任务的一部分(例如每 5 秒一次)。在外部,您可以调用该事件来处理待处理的调度,或者每次超时时您也可以检查待处理的调度。
如果您将超时设置为最小间隔的一小部分(例如 30%),那么您可以对“检查”过程花费的时间进行适当的控制,但是如果您错过了一个间隔,您将有一段合理的时间来进行检查。派遣任务。它还为您提供了合理启动的窗口。
可以通过维护接下来需要发生的 api 调用的有序列表并将超时设置为其中的一部分来完成实现。
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.