一定时间后如何运行python程序的一部分

时间:2019-07-19 18:50:48

标签: python

我想在上午7点时在python程序中运行我的函数。几乎像when函数when time == time:

我不想使用cron,因为我希望它是内部函数而不执行整个脚本

这是我创建的python脚本:

#sprinkler.py file for sprinkler system
#this is the main file for the sprinklerOS

#functions to import for our test_run.py file
import RPi.GPIO as GPIO
import time
import argparse
import sys
import datetime
#how many zones the user/YOU have set up
zone_count = 10
#gpio pins on the raspberry pi for sprinkler system
pin = [12,7,16,11,18,13,22,15,32,29]

#set mode to board meaning the pin number on pi (1-40) instead of gpio number
GPIO.setmode(GPIO.BOARD)

GPIO.setwarnings(False)


#setting up all of the lights or relays as outputs(in a while loop)
for a in range(10):
        GPIO.setup(pin[a],GPIO.OUT)
        GPIO.output(pin[a], GPIO.LOW)



def run_sprinklers():
        for b in range(zone_count):
                run_time = 5
                GPIO.output(pin[b], GPIO.HIGH)
                time.sleep(run_time)
                GPIO.output(pin[b], GPIO.LOW)
                time.sleep(1)

我想在上午7点运行run_sprinklers() 谢谢

1 个答案:

答案 0 :(得分:2)

正如其他人在评论中提到的那样,cron可能是最好的解决方案。但是,如果这是一个持续的过程,并且您不能依靠cron这样的工具,那么计划模块https://github.com/dbader/schedule可能会引起您的兴趣。

import RPi.GPIO as GPIO
import time
import argparse
import sys
import datetime
import schedule

#how many zones the user/YOU have set up
zone_count = 10
#gpio pins on the raspberry pi for sprinkler system
pin = [12,7,16,11,18,13,22,15,32,29]

#set mode to board meaning the pin number on pi (1-40) instead of gpio number
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)


#setting up all of the lights or relays as outputs(in a while loop)
for a in range(10):
        GPIO.setup(pin[a],GPIO.OUT)
        GPIO.output(pin[a], GPIO.LOW)


def run_sprinklers():
        for b in range(zone_count):
                run_time = 5
                GPIO.output(pin[b], GPIO.HIGH)
                time.sleep(run_time)
                GPIO.output(pin[b], GPIO.LOW)
                time.sleep(1)


schedule.every().day.at("7:00").do(run_sprinklers)


while True:
    schedule.run_pending()
    time.sleep(1)