微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在Python中每60秒异步执行一个函数?

如何解决如何在Python中每60秒异步执行一个函数?

您可以尝试threading.Timer类:http : //docs.python.org/library/threading.html#timer- objects。

import threading

def f(f_stop):
    # do something here ...
    if not f_stop.is_set():
        # call f() again in 60 seconds
        threading.Timer(60, f, [f_stop]).start()

f_stop = threading.Event()
# start calling f Now and every 60 sec thereafter
f(f_stop)

# stop the thread when needed
#f_stop.set()

解决方法

我想每60秒在Python上执行一个函数,但是我不想同时被阻塞。

如何异步进行?

import threading
import time

def f():
    print("hello world")
    threading.Timer(3,f).start()

if __name__ == '__main__':
    f()    
    time.sleep(20)

使用此代码,函数f在20秒time.time中每3秒执行一次。最后,它给出了一个错误,我认为这是因为threading.timer尚未被取消。

如何取消呢?

提前致谢!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。