Python:每n秒运行一次代码,并根据情况重新启动计时器 [英] Python: Run code every n seconds and restart timer on condition

查看:224
本文介绍了Python:每n秒运行一次代码,并根据情况重新启动计时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能比我想的要简单,但是我想创建一个计时器,该计时器在达到极限(例如15分钟)后会执行一些代码。

This may be simpler than I think but I'd like to create timer that, upon reaching a limit (say 15 mins), some code is executed.

同时,我想测试一下条件。如果满足条件,则计时器将重置,并且过程将再次开始,否则倒计时将继续。

Meanwhile every second, I'd like to test for a condition. If the condition is met, then the timer is reset and the process begins again, otherwise the countdown continues.

如果在倒计时结束后满足条件,

If the condition is met after the countdown has reached the end, some code is executed and the timer starts counting down again.

这涉及到线程还是可以通过以下方式实现?一个简单的 time.sleep()函数?

Does this involve threading or can it be achieved with a simple time.sleep() function?

推荐答案

描述听起来不错类似于死主电源开关 / 看门狗计时器。它的实现方式取决于您的应用程序:是否有事件循环,是否有阻塞函数,是否需要单独的过程进行适当隔离等?如果代码中没有函数阻塞:

The description sounds similar to a dead main's switch / watchdog timer. How it is implemented depends on your application: whether there is an event loop, are there blocking functions, do you need a separate process for proper isolation, etc. If no function is blocking in your code:

#!/usr/bin/env python3
import time
from time import time as timer

timeout = 900 # 15 minutes in seconds
countdown = timeout # reset the count
while True:
    time.sleep(1 - timer() % 1) # lock with the timer, to avoid drift
    countdown -= 1
    if should_reset_count():
        countdown = timeout # reset the count
    if countdown <= 0: # timeout happened
        countdown = timeout # reset the count
        "some code is executed"

该代码假定从不休眠被打断(注意:在Python 3.5之前,睡眠可能会被信号打断)。该代码还假定没有功能花费大量时间(大约一秒钟)。否则,您应该改用显式的截止日期(相同的代码结构):

The code assumes that the sleep is never interrupted (note: before Python 3.5, the sleep may be interrupted by a signal). The code also assumes no function takes significant (around a second) time. Otherwise, you should use an explicit deadline instead (the same code structure):

deadline = timer() + timeout # reset
while True:
    time.sleep(1 - timer() % 1) # lock with the timer, to avoid drift
    if should_reset_count():
        deadline = timer() + timeout # reset
    if deadline < timer(): # timeout
        deadline = timer() + timeout # reset
        "some code is executed"



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