[英]Python3: Start multiple functions every x, y, z seconds
I'm really new to python and coding in general so I'm sorry if this is a stupid question... I'm working on a python 3 script that will automate a greenhouse with a raspberry pi. 我真的是python和编码的新手,所以如果这是一个愚蠢的问题,我感到很抱歉...我正在研究一个python 3脚本,它将用树莓派自动化温室。 To check on temperature, light, moisture etc. and to upload pictures of the plant I have multiple functions.
要检查温度,光线,湿度等并上传植物的图片,我具有多种功能。 Now I want to call those functions individually after a certain amount of time has passed.
现在,我想在经过一定时间后分别调用这些函数。 So for example call the temperature function every 30 seconds, the light function every 45 and take a picture every 5 minutes.
因此,例如每30秒调用一次温度功能,每45秒调用一次灯光功能,每5分钟拍照一次。 What would be the best way to do this?
最好的方法是什么?
Try something like this: 尝试这样的事情:
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)
Hope it helps. 希望能帮助到你。
This is a minimal scheduler if you want to keep your program very simple. 如果您想使程序保持非常简单,则这是一个最小的调度程序。 Perhaps too basic for a real-world usage, but it shows the concept.
对于现实世界的用法而言,也许太基本了,但它说明了这一概念。
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.