我有一个python程序,希望每5分钟之前30秒执行一次,并且只需要运行30秒。
答案 0 :(得分:1)
与其反复测试是否是正确的时间,不如计算一次等待直到进入睡眠状态所需的时间,以便处理器可以执行其他操作。为此,我们仍然使用datetime
模块和一些简单的数学运算。
from datetime import datetime as dt
from time import sleep
#Calculating sleep interval
t = dt.now()
#seconds in the hour
sec = t.second + t.minute*60
#seconds since the last 5 min interval
sec = sec % 300
#until the next 5 min interval
sec = 300 - sec
#30 sec before that
sec = sec - 30
#if negative we're within 30 sec of 5 minute interval so goto next one
if sec < 0:
sec = sec + 300
sleep(sec)
while True: #loop forever
#with a little re-arranging and boolean math, this can all be condensed to:
t = dt.now()
s = (t.second + 60*t.minute) % 300
sleep(270 - s + 300 * (s >= 270))
#yourFunction()
在非常简单的情况下,这应该可以工作。如果您的程序在任何时候崩溃了,或者计算机重新启动了,或者有许多其他原因,那么最好使用操作系统内置的东西,它会自动重新启动程序,并且可以处理其他情况,例如例如,设置睡眠计时器,或者仅在特定用户登录时才执行。在Windows上是任务计划程序,在Linux上通常是cron,并且启动了OSX(至少根据developer.apple.com)
答案 1 :(得分:0)
如果您在indefintley中运行此代码,建议您按照Aaron的观点来看待superuser.com,apple.stackexchange.com或askubuntu.com。
但是,如果要使用Python编写此代码,则可以使用datetime
模块并查找经过的时间。
from datetime import datetime
import time
def your_function(t1):
i = 0
# For the next 30 seconds, run your function
while (datetime.now() - t1).seconds =< 30:
i += 1
print(i)
time.sleep(1)
# Run indefintely
while True:
# Record the current time
t1 = datetime.now()
while t1:
# Find the elapsed time in seconds
# If the difference is 270 seconds (4 minutes and 30 seconds)
if (datetime.now()-t1).seconds == 270:
your_function(t1)
# Remove t1 and start at the top of the loop again
t1 = None