我怎样才能每次执行python代码

2024-05-28 23:39:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在开发一个“天气记录器”应用程序,它将每小时/每天创建一个日志文件。 这是我的代码:

import Adafruit_DHT as dht
import RPi.GPIO as GPIO
import time
import os
GPIO.setmode(GPIO.BCM)
rainsensorpin = "4"
GPIO.setup(rainsensorpin, GPIO.IN)
def log():
        print "[!] Log action executed, processing it..."
        filename = time.strftime('%d%Y-%m-%d %H:%M:%S')
        humidity, temperature = Adafruit_DHT.read_retry(sensor,pin)
        temp = "{:0.1f}*C".format(temperature)
        hum = "{:0.1f}%".format(humidity)
        state = GPIO.input(rainsensorpin)
        data = "Temp: ", temp, " Hum: ", hum, " Rain: ", state, " Date+Time: ", filename
        os.chdir("logs")
        os.mknod(filename)
        print "[+] Successfully created file: ", filename

有没有办法每小时或每天都执行这段代码?在


Tags: 代码importadafruitgpiotimeosasfilename
2条回答

如果您在linux上,您可以将cron与5 * * * * /usr/bin/wget -O - -q -t 1 http://localhost/cron.php结合使用;如果您在windows上,您可以使用this链接。在

高温

您可以使用apscheduler。有7种调度程序,您可以了解它们here。后台调度程序是我喜欢的一种类型,可用于以下行:

from apscheduler.schedulers.background import BackgroundScheduler
scheduler = BackgroundScheduler()
scheduler.add_job(log, 'cron', hours='0-24', id='my_job_id')
scheduler.start()

相关问题 更多 >

    热门问题