我正在开发一个调度应用程序,在时间表中有许多灯在特定时间打开和关闭,如果我在早上开始计划,所有灯将打开然后在晚上停止,但是有一些灯需要在随机时间停止并再次打开。我已经尝试了一些像APScheduler这样的python包,但它没有停止和恢复特定任务的功能(或者在这个场合下灯)。
这个question使用pickle来停止和恢复,但我不知道如何实现它,有什么方法可以解决这个问题吗?
提前致谢,抱歉我的坏语法。
- UPDATE -
这是一个简单的实现,我不确定这段代码是否正确。
from datetime import datetime
from time import sleep
class Scheduling:
def __init__(self):
self.lamp = {}
def run(self, lamp_id, start, finish):
"""Called one-time only for each lamp"""
self.lamp[lamp_id] = (start, finish)
while True:
if datetime.now().strftime('%H:%M:%S') == start:
sleep(1)
print 'SET LAMP %s ON' % lamp_id
elif datetime.now().strftime('%H:%M:%S') == finish:
sleep(1)
print 'SET LAMP %s OFF' % lamp_id
def stop(self, lamp_id):
print 'SET lamp %s OFF' % lamp_id
def resume(self, lamp_id):
print 'SET lamp %s ON' % lamp_id
finish = self.lamp[lamp_id][1]
while True:
if datetime.now().strftime('%H:%M:%S') == finish:
print 'SET lamp %s OFF' % lamp_id
if __name__ == '__main__':
schedule = Scheduling()
schedule.run(1, '00:00:00', '00:01:00')
答案 0 :(得分:1)
我认为你可能会错误地看待这个问题。将“灯亮”视为要停止和恢复的任务是过于复杂的。真的,你所拥有的是一系列预定的无状态事件;打开一盏灯,关闭一盏灯(也许是拨动灯,如果打开则关闭或关闭灯)。如果您尝试以这种方式对系统进行建模,则可能更容易设置调度程序。
答案 1 :(得分:0)
使用APScheduler并不是一个糟糕的解决方案,我将在此实例中使用它。我要做的是写一个客户触发器。
此触发器将使用客户数据库或数据存储,这很容易从默认内存存储或数据库存储扩展。这有一个标志,是否跳过或不运行特定的工作。因此,现在会发生的事情是当打开/关闭灯泡的任务出现时,客户触发器将检查数据库以查看任务是否打开/关闭并根据其当前状态执行所需的操作。
这可以通过查看Extending APScheduler Documentation。
来完成Interval Trigger Class that would be extended to incorporate your stop/resume logic
The Interface you will need to implement for the customer datastore
编辑:
你的实现有一个问题,即while
循环将进入无限循环,中间没有睡眠,因为你没有处理内部循环部分的else情况并且不睡觉。这会导致单个灯泡的高CPU使用率。