非轮询/非阻塞定时器? [英] Non-polling/Non-blocking Timer?

查看:35
本文介绍了非轮询/非阻塞定时器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我发现的最佳解决方案是使用 sleep() 函数.当计时器到期事件发生时,我想运行我自己的回调函数.有没有任何事件驱动的方法来解决这个问题?

The best solution I've found so far is to just use the sleep() function. I'd like to run my own callback function when the event of a timer expiration happens. Is there any event-driven way to go about it?

from time import sleep

# Sleep for a minute
time.sleep(60)

推荐答案

有一个内置的简单解决方案,使用 线程 模块:

There's a built-in simple solution, using the threading module:

import threading

timer = threading.Timer(60.0, callback)
timer.start()  # after 60 seconds, 'callback' will be called

## (in the meanwhile you can do other stuff...)

您还可以将 args 和 kwargs 传递给您的回调.请参阅此处.

You can also pass args and kwargs to your callback. See here.

这篇关于非轮询/非阻塞定时器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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