Run a python function every second

后端 未结 6 865
我寻月下人不归
我寻月下人不归 2020-12-16 08:08

What I want is to be able to run a function every second, irrelevant of how long the function takes (it should always be under a second). I\'ve considered a number of option

6条回答
  •  孤城傲影
    2020-12-16 08:50

    How about this: After each run, sleep for (1.0 - launch interval) seconds. You can change the terminate condition by changing while True:. Although if the your function takes more than 1 second to run, this will go wrong.

    from time import time, sleep
    
    while True:
        startTime = time()
        yourFunction()
        endTime = time()-startTime
        sleep(1.0-endTime)
    

提交回复
热议问题