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()
相关推荐
m沐沐2 分钟前
【机器学习】矿物识别系统实战——六种填充方法×六种模型全面对比
人工智能·python·深度学习·机器学习·矿物识别
软糖姐姐11 分钟前
Python:__closure__ 详解
python·闭包·__closure__·自由变量·cell对象
月光船幽幽16 分钟前
四层公理框架驱动AI健康诊断
人工智能·python·科技·算法·安全
zmzb010320 分钟前
C++课后习题训练记录Day176
开发语言·c++
Rabitebla25 分钟前
C++ STL 之 set 详解:从底层红黑树到实际应用
开发语言·数据结构·c++·算法·leetcode
520拼好饭被践踏28 分钟前
JAVA+Agent学习day26
java·开发语言·数据结构·学习·agent
郝学胜-神的一滴39 分钟前
力扣 692:巧用小顶堆高效求解前K个高频单词
java·数据结构·python·程序人生·算法·leetcode·职场和发展
栈溢出的浪漫40 分钟前
Python单元测试框架覆盖率-Coverage
python·单元测试·工具·覆盖率·coverage
淼澄研学42 分钟前
Python构建AI应用:从环境配置到FastAPI部署的5个实操步骤
人工智能·python·fastapi
157092511341 小时前
优先队列:从Java源码到实战
开发语言·python