如何在 Python 中每 60 秒异步执行一次函数? [英] How to execute a function asynchronously every 60 seconds in Python?

查看:37
本文介绍了如何在 Python 中每 60 秒异步执行一次函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 Python 上每 60 秒执行一次函数,但我不想同时被阻止.

I want to execute a function every 60 seconds on Python but I don't want to be blocked meanwhile.

如何异步执行?

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 没有被取消.

With this code, the function f is executed every 3 seconds within the 20 seconds time.time. At the end it gives an error and I think that it is because the threading.timer has not been canceled.

如何取消?

提前致谢!

推荐答案

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

You could try the threading.Timer class: 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()

这篇关于如何在 Python 中每 60 秒异步执行一次函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆