简体   繁体   English

如何每隔 n 秒调用一次 function?

[英]How to call a function every n seconds?

If I do:如果我做:

def my_api_query():
    pass

while True:
    my_api_query()
    time.sleep(5)

This would work like execution time of my_api_query() plus 5 seconds, which is longer than 5 seconds.这就像my_api_query()的执行时间加上 5 秒,比 5 秒长。

I want one iteration to be executed exactly every 5th second.我希望每 5 秒准确执行一次迭代。

How can I implement it in Python 3?如何在 Python 3 中实现它?

I think I found a solution, need to test it, any other suggestions are welcome:我想我找到了解决方案,需要对其进行测试,欢迎提出任何其他建议:

import threading

def my_api_query():
  threading.Timer(5.0, my_api_query).start()
  some code

my_api_query()

Another solution is quite clumsy, but should be working另一个解决方案非常笨拙,但应该可以工作

import time
nexttime = time.time()
while True:
    my_api_query()          # take t sec
    nexttime += 10
    sleeptime = nexttime - time.time()
    if sleeptime > 0:
        time.sleep(sleeptime)

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

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