我正在尝试用Python实现一个带有闹钟的数字时钟。现在我想知道什么是实现闹钟功能的最佳方法。我找到了几个类似的项目,主要集中在闹钟功能上。他们通常只计算到下一次醒来的时间,然后再按计算出的秒数进入睡眠状态。
见here和here:
我的问题是,我也实现了一个正常的时钟和显示时间。因此我必须每秒更新一次时钟。在这个循环中,我检查是否不应该触发警报。为此,我正在寻找一个简单而有效的实现闹钟功能的表格。
在第一个例子的启发下,我最终得出这样的结论:#!/usr/bin/python
import time
import datetime
class Clock:
def __init__(self):
# set the initial time
self.hour = 0
self.minute = 0
self.second = 0
# the update interval in seconds
self.update_interval = 1
self.keep_running = True
# the instance of the alarm
self.alarm = AlarmClock()
def run(self):
while self.keep_running:
# update the clock time
now = datetime.datetime.now()
self.hour = now.hour
self.minute = now.minute
self.second = now.second
# now check if the alarm should not be started
if self.alarm.is_active():
if self.alarm.time_till_next_alarm() < 1:
# has to be done in separate thread
self.alarm.on_wake_up()
time.sleep(self.update_interval)
def get_alarm(self):
return self.alarm
class AlarmClock:
def __init__(self, hour=8, minute=0):
# We start with predefined alarm at 8:00 which is not active
self.hour = hour
self.minute = minute
self.active = False
# the alarm should be stopped after some time (1h 00min)
self.duration = datetime.timedelta(hours=1, minutes=0)
def time_till_next_alarm(self):
now = datetime.datetime.now() # get current date & time
# separate date and time from each other:
currdate = datetime.date(now.year, now.month, now.day)
currtime = datetime.time(now.hour, now.minute)
alarmtime = self.get_wake_up_time()
# add today's date onto the alarm time entered
alarmdatetime = datetime.datetime.combine(currdate, alarmtime)
if alarmtime <= currtime: # if the alarm time is less than the current time set clock for tomorrow
alarmdatetime += datetime.timedelta(hours=24)
return alarmdatetime - now
def set_time(self, hour, minute):
self.hour = hour
self.minute = minute
def activate(self):
self.active = True
def deactivate(self):
self.active = False
def is_active(self):
return self.active
def on_wake_up(self):
# start the wake up
print 'Wake up!'
#Execution starts here
if __name__ == '__main__':
clock = Clock()
clock.get_alarm().activate()
clock.get_alarm().set_time(8,0)
clock.run()
有没有更好或更少的计算要求的实现?
编辑:
我想在7段式液晶显示器上显示时间,here are some details about the part.因此,我在每次更新液晶显示器时都用run()方法写入数字# set the tens and ones of hours and minutes
self.display.set_digit(0, int(self.hour / 10)) # Tens
self.display.set_digit(1, self.hour % 10) # Ones
self.display.set_digit(2, int(self.minute / 10)) # Tens
self.display.set_digit(3, self.minute % 10) # Ones
编辑2:
尽管Adafruit提供的python库允许您设置整个显示的闪烁频率,但我希望以1Hz的频率闪烁冒号,以表示秒的频率。# Toggle colon at 1Hz
self.display.set_colon(self.second % 2)