所以我正在编写一个代码,在其中创建嵌套计时器,用户只需输入他们想要执行某操作的时间(以分钟为单位)。该程序将时间划分为 x 个分钟的时间块,并在该块内发出随机警报。我已经有了代码来计算出时间块的数量以及在这些时间块内的哪分钟触发警报。但是,我坚持创建一个函数来概括时间块和闹钟时间的创建。这样每个闹钟都会在每个时间段内指定的分钟数后响起。我知道如何设置第一个警报,但不知道如何设置通用警报。我将如何设置第一个计时器如下。在下面的示例中,总计为 60 分钟,并且在 15 分钟的时间段内,警报将在每 15 分钟的时间段内的特定分钟标记处响起。
# t is the desired time in minutes
t = 60
#total work time in seconds
ts = t * 60
# the times in minutes each alarm will go off in a 15-minute block
alarms = [5 , 3 , 8 , 10]
alarm_1 = alarms[0] * 60
#alarm1 = ts - (alarms[0] * 60)
alarm_return = 30
while alarm1 > 0:
# Timer represents time left on countdown
alarm_1_timer = datetime.timedelta(seconds = alarm_1)
# prints time left
print(alarm_1_timer, end="\r")
# Delays the program one second
time.sleep(1)
# Reduces total time by one second
alarm_1-= 1
print("alarm 1")
while alarm_return > 0:
# Timer represents the time left on countdown
alarm1_return_timer = datetime.timedelta(seconds = alarm_return)
print(alarm1_return_timer, end="\r")
# Delays the program one second
time.sleep(1)
# Reduces total time by one second
alarm_return -= 1
print("alarm_return")
我认为你应该使用 PriorityQueue。对象在队列中排序并按最小的优先顺序提取。以任意顺序输入时间,最早的时间将首先被提取。然后计算等待该时间发生的时间。
import datetime as dt
import queue
import time
def add_alarm(q, minutes):
# Do time math in UTC. DST will mess up other time zones.
q.put((dt.datetime.now(tz=dt.timezone.utc) + dt.timedelta(seconds=minutes * 60)))
def wait_next_alarm(q):
try:
a = q.get_nowait()
except queue.Empty:
# no alarms in queue
return False
# How long to wait until alarm.
diff = a - dt.datetime.now(tz=dt.timezone.utc)
# Check in case the alarm is passed.
if diff.total_seconds() > 0:
# wait for alarm time
time.sleep(diff.total_seconds())
return True
q = queue.PriorityQueue()
for alarm in (5, 3, 8, 10):
add_alarm(q, alarm)
start = dt.datetime.now()
while wait_next_alarm(q):
print(dt.datetime.now() - start) # how long did we wait?
输出:
0:03:00.001511
0:05:00.005524
0:08:00.002192
0:10:00.007208