我怎样才能每小时执行 python 代码
how can i execute python code every hour
我正在开发一个 "WeatherLogger" 应用程序,它将每隔 hour/day 创建一个日志文件。
这是我的代码:
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
有没有办法每小时或每天执行此代码?
如果你在 linux 你可以使用 cron 和类似 5 * * * * /usr/bin/wget -O - -q -t 1 http://localhost/cron.php
的东西,如果你在 windows 你使用 this link.
HTH
您可以使用 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()
我正在开发一个 "WeatherLogger" 应用程序,它将每隔 hour/day 创建一个日志文件。 这是我的代码:
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
有没有办法每小时或每天执行此代码?
如果你在 linux 你可以使用 cron 和类似 5 * * * * /usr/bin/wget -O - -q -t 1 http://localhost/cron.php
的东西,如果你在 windows 你使用 this link.
HTH
您可以使用 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()