【问题标题】:Python3: Start multiple functions every x, y, z seconds [duplicate]Python3:每x,y,z秒启动多个函数[重复]
【发布时间】:2018-02-07 11:18:21
【问题描述】:

我对python和一般编码真的很陌生,所以如果这是一个愚蠢的问题,我很抱歉...... 我正在研究一个 python 3 脚本,它将用树莓派自动化温室。要检查温度、光线、湿度等并上传植物图片,我有多种功能。现在我想在经过一定时间后单独调用这些函数。 例如,每 30 秒调用一次温度函数,每 45 秒调用一次光照函数,每 5 分钟调用一次照片。 最好的方法是什么?

【问题讨论】:

  • 看看threading 模块,特别是Timer 类。
  • 是的线程在这里将是不错的选择
  • 线程确实是一种可能的解决方案,计划作业是另一种解决方案。在所有情况下,请注意,除非您有硬实时操作系统,否则“每 30 秒”等概念将是非常近似的。在这里不应该是一个问题,但您可能仍要记住这一点。哦,是的:最好在启动下一个调用之前确保给定调用已完成,否则您可能会遇到竞争条件或其他并发问题。

标签: python loops time


【解决方案1】:

试试这样的:

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)

希望对你有帮助。

【讨论】:

  • 谢谢你们,这正是我想要的。我一拿到 pi 就会尝试这两种方法:)
【解决方案2】:

如果您想保持程序非常简单,这是一个最小的调度程序。对于实际使用而言,可能过于基础,但它显示了这个概念。

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()

【讨论】:

  • 谢谢你们,这正是我想要的。我一拿到 pi 就会尝试这两种方法:)
猜你喜欢
  • 2015-05-07
  • 2013-02-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-05
  • 1970-01-01
  • 2015-10-09
  • 1970-01-01
相关资源
最近更新 更多