每 x 秒重复执行一个函数的最佳方法是什么? [英] What is the best way to repeatedly execute a function every x seconds?

查看:57
本文介绍了每 x 秒重复执行一个函数的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想永远每 60 秒在 Python 中重复执行一个函数(就像 NSTimer 在目标 C 中).此代码将作为守护程序运行,实际上就像使用 cron 每分钟调用一次 python 脚本一样,但不需要用户进行设置.

I want to repeatedly execute a function in Python every 60 seconds forever (just like an NSTimer in Objective C). This code will run as a daemon and is effectively like calling the python script every minute using a cron, but without requiring that to be set up by the user.

这个关于用 Python 实现的 cron 的问题,该解决方案似乎有效地 sleep() 持续 x 秒.我不需要这么高级的功能,所以也许这样的东西会起作用

In this question about a cron implemented in Python, the solution appears to effectively just sleep() for x seconds. I don't need such advanced functionality so perhaps something like this would work

while True:
    # Code executed here
    time.sleep(60)

这段代码有什么可预见的问题吗?

Are there any foreseeable problems with this code?

推荐答案

如果您的程序还没有事件循环,请使用 sched 模块,它实现了一个通用的事件调度器.

If your program doesn't have a event loop already, use the sched module, which implements a general purpose event scheduler.

import sched, time
s = sched.scheduler(time.time, time.sleep)
def do_something(sc): 
    print("Doing stuff...")
    # do your stuff
    s.enter(60, 1, do_something, (sc,))

s.enter(60, 1, do_something, (s,))
s.run()

如果您已经在使用事件循环库,例如 asynciotriotkinterPyQt5gobjectkivy 和许多其他 - 只需使用您现有的事件循环库的方法来安排任务.

If you're already using an event loop library like asyncio, trio, tkinter, PyQt5, gobject, kivy, and many others - just schedule the task using your existing event loop library's methods, instead.

这篇关于每 x 秒重复执行一个函数的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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