执行周期性动作 [英] Executing periodic actions

查看:81
本文介绍了执行周期性动作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Windows 上工作.我想每 10 秒执行一次函数 foo().
我该怎么做?

I am working on Windows. I want to execute a function foo() every 10 seconds.
How do I do this?

推荐答案

foo()的末尾,创建一个调用foo()的Timer 10 秒后自身.
因为,Timer 创建了一个新的 thread 来调用 foo().
你可以在不被屏蔽的情况下做其他事情.

At the end of foo(), create a Timer which calls foo() itself after 10 seconds.
Because, Timer create a new thread to call foo().
You can do other stuff without being blocked.

import time, threading
def foo():
    print(time.ctime())
    threading.Timer(10, foo).start()

foo()

#output:
#Thu Dec 22 14:46:08 2011
#Thu Dec 22 14:46:18 2011
#Thu Dec 22 14:46:28 2011
#Thu Dec 22 14:46:38 2011

这篇关于执行周期性动作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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