python定时任务,定时爬取水质和天气

定时爬取水质和天气

代码

c 复制代码
from apscheduler.schedulers.background import BackgroundScheduler
import requests
import datetime

urlweather = "http://localhost:8000/CrwalingViewWeather"  # 天气接口
urlwater = "http://localhost:8000/CrwalingViewWater/"  # 水质接口

def fetch_weather():
    print("正在获取天气数据...", datetime.datetime.now())
    try:
        response = requests.get(urlweather)
        if response.status_code == 200:
            print("天气数据获取成功")
        else:
            print("天气数据获取失败")
    except Exception as e:
        print(f"获取天气数据时发生错误: {e}")

def fetch_water_quality():
    print("正在获取水质数据...", datetime.datetime.now())
    try:
        response = requests.get(urlwater)
        if response.status_code == 200:
            print("水质数据获取成功")
        else:
            print("水质数据获取失败")
    except Exception as e:
        print(f"获取水质数据时发生错误: {e}")

scheduler = BackgroundScheduler()

# 每小时的第10分钟执行
scheduler.add_job(fetch_weather, 'cron', hour='*', minute=40)
# 每小时的第20分钟执行
scheduler.add_job(fetch_water_quality, 'cron', hour='*', minute=20)

scheduler.start()

try:
    # 模拟长时间运行
    while True:
        datetime.datetime.now()
except (KeyboardInterrupt, SystemExit):
    scheduler.shutdown()
相关推荐
Warson_L16 小时前
Python `Annotated` 与 LangGraph Reducer 学习笔记
python
韩师傅16 小时前
海天线算法的前世今生
python·计算机视觉
韩师傅16 小时前
当你的甲方设备过烂,要如何快速出效果?
python·计算机视觉
Warson_L16 小时前
LangGraph的MessageState and HumanMessage
python
韩师傅17 小时前
当你的甲方吐槽天空不够蓝,你应该如何应对
python·计算机视觉
Warson_L17 小时前
python的类&继承
python
Warson_L17 小时前
类型标注/type annotation
python
ThreeS19 小时前
手搓MiniVLA全实战教程-一步一步用pytorch解释原理与思路
人工智能·python
金銀銅鐵21 小时前
[Python] 模 n 乘法的逆元计算器
python·数学·游戏