Python APScheduler运行时间错误:无法在解释器关闭后安排新的未来



我有一个带温度传感器的Raspberry Pi 4(DHT22(,我制作了一个脚本来在网站上显示数据(node.js(。最近,脚本工作了,但在我重新安装RPIos lite后,总是会出现这个错误:

Error submitting job "saveTempDate (trigger: cron[minute='*/55'], next run at: 2021-11-18 15:55:00 GMT)" to executor "default"
Traceback (most recent call last):
File "/usr/local/lib/python3.9/dist-packages/apscheduler/schedulers/base.py", line 979, in _process_jobs
executor.submit_job(job, run_times)
File "/usr/local/lib/python3.9/dist-packages/apscheduler/executors/base.py", line 71, in submit_job
self._do_submit_job(job, run_times)
File "/usr/local/lib/python3.9/dist-packages/apscheduler/executors/pool.py", line 28, in _do_submit_job
f = self._pool.submit(run_job, job, job._jobstore_alias, run_times, self._logger.name)
File "/usr/lib/python3.9/concurrent/futures/thread.py", line 163, in submit
raise RuntimeError('cannot schedule new futures after '
RuntimeError: cannot schedule new futures after interpreter shutdown
Error submitting job "saveTempDate (trigger: cron[minute='*/5'], next run at: 2021-11-18 15:55:00 GMT)" to executor "default"
Traceback (most recent call last):
File "/usr/local/lib/python3.9/dist-packages/apscheduler/schedulers/base.py", line 979, in _process_jobs
executor.submit_job(job, run_times)
File "/usr/local/lib/python3.9/dist-packages/apscheduler/executors/base.py", line 71, in submit_job
self._do_submit_job(job, run_times)
File "/usr/local/lib/python3.9/dist-packages/apscheduler/executors/pool.py", line 28, in _do_submit_job
f = self._pool.submit(run_job, job, job._jobstore_alias, run_times, self._logger.name)
File "/usr/lib/python3.9/concurrent/futures/thread.py", line 163, in submit
raise RuntimeError('cannot schedule new futures after '
RuntimeError: cannot schedule new futures after interpreter shutdown

这是数据保存脚本(temperaturelog.py(:

from __future__ import division
from apscheduler.schedulers.background import BackgroundScheduler # type: ignore
import datetime
import json
import os.path
import time
import math
import dht
import weather
print("Temperature logging started.")
dht.startDataLoading()
def get_cpu_temperature():
f = open("/sys/class/thermal/thermal_zone0/temp", "r")
t = f.readline()
cpuTemp = int(t)
return (cpuTemp / 1000)
def saveTempDate():
print("saving...")
curMs = time.time()
msPassedToday = curMs % (24*60*60*1000)
dt = datetime.datetime.now()
if not(os.path.isfile("/./home/pi/RPIweb/www/data/tempandhumidity/" + (f"{dt.year:04d}" + f"{dt.month:02d}" + f"{dt.day:02d}") + ".json")):
with open("/./home/pi/RPIweb/www/data/tempandhumidity/" + (f"{dt.year:04d}" + f"{dt.month:02d}" + f"{dt.day:02d}") + ".json", "w") as file:
preData = {}
for i in range(math.floor(msPassedToday / 300000)):
preData[f"{math.floor(i/12):02d}:{(i%12)*5:02d}"] = [0, 0, 0, 0]
print(preData)
file.write("{"history": " + json.dumps(preData) + ", "current": [0,0,0,0]}")
with open("/./home/pi/RPIweb/www/data/tempandhumidity/" + (f"{dt.year:04d}" + f"{dt.month:02d}" + f"{dt.day:02d}") + ".json", "r") as file:
data = json.loads(file.read())
data["history"][f"{dt.hour:02d}" + ":" + f"{dt.minute:02d}"] = [dht.getData()[0], weather.getCurrentWeather()["main"]["temp"], get_cpu_temperature(), dht.getData()[1]]
data["current"] = [dht.getData()[0], weather.getCurrentWeather()["main"]["temp"], get_cpu_temperature(), dht.getData()[1]]
with open("/./home/pi/RPIweb/www/data/tempandhumidity/" + (f"{dt.year:04d}" + f"{dt.month:02d}" + f"{dt.day:02d}") + ".json", "w") as file:
file.write(json.dumps(data))

# Setup scheduler for saving temperature
sched = BackgroundScheduler(daemon=True)
sched.add_job(saveTempDate, trigger="cron", hour="*")
sched.add_job(saveTempDate, trigger="cron", minute="*/05")
sched.add_job(saveTempDate, trigger="cron", minute="*/10")
sched.add_job(saveTempDate, trigger="cron", minute="*/15")
sched.add_job(saveTempDate, trigger="cron", minute="*/20")
sched.add_job(saveTempDate, trigger="cron", minute="*/25")
sched.add_job(saveTempDate, trigger="cron", minute="*/30")
sched.add_job(saveTempDate, trigger="cron", minute="*/35")
sched.add_job(saveTempDate, trigger="cron", minute="*/40")
sched.add_job(saveTempDate, trigger="cron", minute="*/45")
sched.add_job(saveTempDate, trigger="cron", minute="*/50")
sched.add_job(saveTempDate, trigger="cron", minute="*/55")
sched.start()

这是dht.py:

import time
import board # type: ignore
import adafruit_dht # type: ignore
import threading

# Initial the dht device, with data pin connected to:
# dhtDevice = adafruit_dht.DHT22(board.D4)

# you can pass DHT22 use_pulseio=False if you wouldn't like to use pulseio.
# This may be necessary on a Linux single board computer like the Raspberry Pi,
# but it will not work in CircuitPython.
dhtDevice = adafruit_dht.DHT22(board.D4, use_pulseio=False)
global temp, hum
def getData():
global temp, hum
return [temp, hum]
def dataLoadingLoop():
global temp, hum
while True:
try:
# Print the values to the serial port
temp = dhtDevice.temperature
hum = dhtDevice.humidity  

except RuntimeError as error:
# Errors happen fairly often, DHT's are hard to read, just keep going
print(error.args[0])
time.sleep(2.0)
continue
except Exception as error:
dhtDevice.exit()
raise error

time.sleep(10.0)
def startDataLoading():
global temp, hum
temp = 0
hum = 0
dataThread = threading.Thread(target=dataLoadingLoop)
dataThread.start()

这是我在这里的第一个问题,我希望我写对了。谢谢

更新:我发现APscheduler不能在Python 3.10上工作,所以我把我的Python版本改为3.7,现在可以工作了。

最新更新