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

2024-04-20 05:58:05 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我怎样才能异步完成呢?

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

我怎样才能取消呢?

提前谢谢!


Tags: 函数代码nameimporthelloworldiftime
3条回答

最简单的方法是创建一个每60秒运行一次的后台线程。一个简单的实现是:

class BackgroundTimer(Thread):   
   def run(self):
      while 1:
        Time.sleep(60)
        # do something


# ... SNIP ...
# Inside your main thread
# ... SNIP ...

timer = BackgroundTimer()
timer.start()

显然,如果“做某事”需要很长时间,你需要在你的睡眠陈述中适应它。但这是一个很好的近似值。

你可以试试线程。计时器类: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()

我四处搜索,找到了Pythoncircuits框架,这使得等待成为可能 对于一个特定的事件。

电路的.callEvent(self, event, *channels)方法包含一个fire和suspend-until响应功能,文档中说:

Fire the given event to the specified channels and suspend execution until it has been dispatched. This method may only be invoked as argument to a yield on the top execution level of a handler (e.g. "yield self.callEvent(event)"). It effectively creates and returns a generator that will be invoked by the main loop until the event has been dispatched (see :func:circuits.core.handlers.handler).

我希望你和我一样觉得它有用:)
/问候

相关问题 更多 >