睡眠到下一个 15 分钟的每小时间隔(00:00、00:15、00:30、00:45)



我需要我的脚本休眠到下一个 15 分钟的每小时间隔,例如整点、四分之一过去、半点和四分之一。

它看起来像这样

While True:
//do something
sleepy_time = //calculate time to next interval
time.sleep(sleepy_time)

您可以编写一系列 if 语句来检查一小时后的当前分钟数是多少,然后执行"如果当前<15"和"如果当前<30"等,但这似乎很混乱且效率低下。

编辑:基于@martineau的答案,这是我使用的代码。

import datetime, time
shouldRun = True
if datetime.datetime.now().minute not in {0, 15, 30, 45}:
shouldRun = False
# Synchronize with the next quarter hour.
while True:
if shouldRun == False:
current_time = datetime.datetime.now()
seconds = 60 - current_time.second
minutes = current_time.minute + 1
snooze = ((15 - minutes%15) * 60) + seconds
print('minutes:', minutes, 'seconds', seconds, ' sleep({}):'.format(snooze))
localtime = time.asctime( time.localtime(time.time()))
print("sleeping at " + localtime)
time.sleep(snooze)  # Sleep until next quarter hour.
shouldRun = True
else:
localtime = time.asctime( time.localtime(time.time()))
print("STUFF HAPPENS AT " + localtime)
shouldRun = False

他的答案与此之间的区别在于,每个间隔仅运行一次 else 块,然后如果分钟仍在 0、15、30、45 间隔上,则计算额外的秒数以添加到分钟睡眠直到下一个间隔。

您可以使用

datetime来实现此目的...

调用datetime.datetime.now()将返回一个datetime,您可以使用.minute使当前minute通过hour

一旦我们有minutes数超过hour,我们可以modulo15这样做,以使minutes15的下一个间隔。

从这里开始,只需60minutes次数(一分钟内60秒)调用time.sleep()

此代码可能如下所示:

import datetime, time
minutesToSleep = 15 - datetime.datetime.now().minute % 15
time.sleep(minutesToSleep * 60)
print("time is currently at an interval of 15!")

time.sleep(15*60 - time.time() % (15*60))

15*60是每 15 分钟的秒数。

time.time() % (15*60)是当前 15 分钟帧中经过的秒数(因为根据定义,时间 0 是 00:00)。它从 XX:00、XX:15、XX:30、XX:45 的 0 增长到 15*60-1(实际上,15*60-0.(0)1— 取决于时间测量的精度),然后再次从 0 开始增长。

15*60 - time.time() % (15*60)是距离 15 分钟帧结束的剩余秒数。使用基本数学计算,它从 15*60 减少到 0。

所以,你需要睡那么几秒钟。

但是,请记住,睡眠不会很精确。处理测量time.time()之间的内部指令需要一些时间,并且实际上在系统级别调用time.sleep()。可能只有几分之一秒。但在大多数情况下,这是可以接受的。

另外,请记住,time.sleep()并不总是睡多久。它可以通过发送到进程的信号(例如,SIGALRM,SIGUSR1,SIGUSR2等)来唤醒。因此,除了睡觉之外,还要检查time.sleep()后是否达到了正确的时间,如果没有,请再次睡觉。

我不认为@Joe Iddon的回答是完全正确的,尽管它很接近。试试这个(注意我注释掉了我不想运行的行,并添加了一个for循环来测试minute的所有可能值):

import datetime, time
# Synchronize with the next quarter hour.
#minutes = datetime.datetime.now().minute
for minutes in range(0, 59):
if minutes not in {0, 15, 30, 45}:
snooze = 15 - minutes%15
print('minutes:', minutes, ' sleep({}):'.format(snooze * 60))
#time.sleep(snooze)  # Sleep until next quarter hour.
else:
print('minutes:', minutes, ' no sleep')
import time
L = 15*60
while True:
#do something
#get current timestamp as an integer and round to the
#nearest larger or equal multiple of 15*60 seconds, i.e., 15 minutes
d = int(time.time())
m = d%L        
sleepy_time = 0 if m == 0 else (L - m)
print(sleepy_time)
time.sleep(sleepy_time)
import schedule
import time
# Define a function named "job" to print a message
def job():
print("Job is running.")
# Set the interval for running the job function to 15 minutes
interval_minutes = 15
# Loop over the range of minutes with a step of interval_minutes
for minute in range(0, 60, interval_minutes):
# Format the time string to be in the format of "MM:SS"
time_string = f"{minute:02d}:00" if minute < 60 else "00:00"
# Schedule the job function to run at the specified time every hour
schedule.every().hour.at(time_string).do(job)
# Infinite loop to keep checking for any pending job
while True:
schedule.run_pending()
# Sleep for 1 second to avoid high CPU usage
time.sleep(1)

相关内容

最新更新