2024-06-13 16:46:08 发布
网友
我对python和一般的代码非常陌生,所以如果这是一个愚蠢的问题,我很抱歉。。。 我正在开发一个python3脚本,它将用一个树莓pi自动化温室。检查温度、光线、湿度等,上传植物图片,我有多种功能。现在我想在一段时间后单独调用这些函数。 例如,每30秒调用一次温度函数,每45秒调用一次灯光函数,每5分钟拍一张照片。 最好的办法是什么?你知道吗
尝试以下操作:
import logging from threading import Timer logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(message)s') CHK_TMP_IVAL = 30.0 CHK_LGHT_IVAL = 45.0 TAKE_PIC_IVAL = 5*60.0 def check_temp(): logging.info('Checking temperature...') def check_light(): logging.info('Checking lighting...') def take_pic(): logging.info('Taking picture...') def schedule_timing(interval, callback): timer = Timer(interval, callback) timer.start() return timer if __name__ == '__main__': logging.info('Start execution...') t1 = schedule_timing(CHK_TMP_IVAL, check_temp) t2 = schedule_timing(CHK_LGHT_IVAL, check_light) t3 = schedule_timing(TAKE_PIC_IVAL, take_pic) while True: if t1.finished.is_set(): t1 = schedule_timing(CHK_TMP_IVAL, check_temp) if t2.finished.is_set(): t2 = schedule_timing(CHK_LGHT_IVAL, check_light) if t3.finished.is_set(): t3 = schedule_timing(TAKE_PIC_IVAL, take_pic)
希望有帮助。你知道吗
这是一个最小的调度程序,如果你想让你的程序非常简单。也许对于现实世界的用法来说太基本了,但它显示了这个概念。你知道吗
import heapq import time class Sched: def __init__(self): self._queue = [] def later(self, func, *args, delay): heapq.heappush(self._queue, (time.time() + delay, func, args)) def loop(self): while True: ftime, func, args = heapq.heappop(self._queue) time.sleep(max(0.0, ftime - time.time())) func(*args) sched = Sched() def f2(): sched.later(f2, delay=2.0) print("2 secs") def f5(): sched.later(f5, delay=5.0) print("5 secs") f2() f5() sched.loop()
尝试以下操作:
希望有帮助。你知道吗
这是一个最小的调度程序,如果你想让你的程序非常简单。也许对于现实世界的用法来说太基本了,但它显示了这个概念。你知道吗
相关问题 更多 >
编程相关推荐