如何安排c函数完全运行每一分钟

时间:2017-11-02 05:25:59

标签: c pthreads scheduled-tasks

我有一个使用pthread创建的线程应该每分钟运行一次。如何在c程序中执行此操作以便每分钟运行一次.sleep doent解决了我的问题。

1 个答案:

答案 0 :(得分:2)

我假设(a)你的意思是sleep并不好,因为如果你在七秒钟的工作后睡了60秒,那就不是每一分钟。< / p>

因此,无论工作需要多长时间,都可以使用(伪代码):

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

减少睡眠是为了确保您在输入新分钟后尽快运行有效负载。