def main():
while True:
if is_true_month(): # 检查是否为每年的1月份、4月份、7月份、10月份的凌晨1:00,判断到min
get_new_history_data # 获取最新的3个月左右的历史数据
train model # 进行模型训练
save model # 保存模型 在之前模型保存的位置直接覆盖
if is_21_oclock(): # 检查是否为晚上九点钟
get_forecast_data # 通过API接口获取次日96点的预报气象数据
save_forecast_data # 将预报的气象数据保存起来
get_save_model and pv_predict获取保存的模型参数,对获取的预报气象数据进行光伏发电功率预测
save predict pv_power # 保存预测的光伏发电功率
time.sleep(3600*23) # 等待23h,避免重复光伏预测
time.sleep(60) # 等待1min后再次检查
if __name__ == "__main__":
main()
有问题:
①问题在与要是进入每天晚上九点后,等待23小时,不管怎样都到不到这几个月1日凌晨1点的判断
②增加全局异常捕获,然后在等待,这样程序不不容易崩
修改:
import threading
import time
import pandas as pd
from sqlalchemy import create_engine
import requests
import joblib
# 数据库连接配置
db_connection_str = 'dialect+driver://username:password@host:port/dbname'
engine = create_engine(db_connection_str)
# 模型训练和保存
def train_model():
try:
# 获取最新的3个月历史数据
df = pd.read_sql('SELECT * FROM history_data WHERE timestamp > NOW() - INTERVAL 3 MONTH', engine)
# 模型训练逻辑
# model = ...
# model.fit(df.features, df.labels)
# 保存模型
joblib.dump(model, 'model.pkl')
# 安排下一次训练
threading.Timer(time_interval, train_model).start()
except Exception as e:
print(f"Error in train_model: {e}")
# 获取预报气象数据
def get_forecast_data():
try:
response = requests.get(' ')
data = response.json()
# 保存预报数据
df = pd.DataFrame(data)
df.to_sql('forecast_data', engine, if_exists='append')
# 安排下一次获取预报数据
threading.Timer(one_day, get_forecast_data).start()
except Exception as e:
print(f"Error in get_forecast_data: {e}")
# 光伏发电预测
def predict_pv_power():
try:
# 加载模型
model = joblib.load('model.pkl')
# 获取最新的预报数据
df = pd.read_sql('SELECT * FROM forecast_data ORDER BY timestamp DESC LIMIT 1', engine)
# 进行预测
prediction = model.predict(df.features)
# 保存预测结果
df['prediction'] = prediction
df.to_sql('pv_predictions', engine, if_exists='append')
# 安排下一次预测
threading.Timer(one_day, predict_pv_power).start()
except Exception as e:
print(f"Error in predict_pv_power: {e}")
# 定义时间间隔
time_interval = 3 * 30 * 24 * 60 * 60 # 3个月的秒数
one_day = 24 * 60 * 60 # 一天的秒数
# 启动定时任务
train_model()
get_forecast_data()
predict_pv_power()
上述这种方式应该更好吧。
上述这种,程序容易崩,不建议用