【发布时间】:2017-11-02 05:25:58
【问题描述】:
我有一个使用 pthread 创建的线程应该每分钟运行一次。如何在 c 程序中执行此操作以每分钟运行一次。sleep 不能解决我的问题。
【问题讨论】:
-
代码在哪里?
-
阅读time(7)然后思考一下。
标签: c pthreads scheduled-tasks
我有一个使用 pthread 创建的线程应该每分钟运行一次。如何在 c 程序中执行此操作以每分钟运行一次。sleep 不能解决我的问题。
【问题讨论】:
标签: c pthreads scheduled-tasks
我假设(a) 你的意思是 sleep 不好,因为如果你在完成 7 秒的工作后睡 60 秒,那不会是每一分钟。
因此,无论工作需要多长时间,为了每分钟都走完,您可以使用类似(伪代码):
def threadFn():
lastTime = now() # or now() - 60 to run first one immediately.
do forever:
currTime = now()
if currTime - lastTime >= 60:
lastTime = currTime
doPayload()
sleep one second
这当然有缺点,如果你的工作需要超过一分钟,它的下一次迭代就会被延迟。但是,不必处理多个并发作业,这可能是最好的。
(a) 这对我来说似乎是最有可能的,但如果您包含代码和/或添加了关于原因的详细信息,我可能不需要做出这样的假设 这是个问题 :-)
作为另一种可能性,要确保它仅在 hh:mm:00 运行(即,恰好在分钟切换时),您可以做一些细微的变化:
def threadFn():
lastTime = now() - 1 # Ensure run at first hh:mm:00.
do forever:
currTime = now()
currSec = getSecond(currTime) # using C's localtime()
if currSec == 0 and currTime != lastTime:
lastTime = currTime
doPayload()
sleep one tenth of a second
减少睡眠是为了确保您在进入新的分钟后尽快运行有效负载。
【讨论】: