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()
相关推荐
databook19 小时前
Manim实现脉冲闪烁特效
后端·python·动效
程序设计实验室20 小时前
2025年了,在 Django 之外,Python Web 框架还能怎么选?
python
倔强青铜三21 小时前
苦练Python第46天:文件写入与上下文管理器
人工智能·python·面试
用户2519162427111 天前
Python之语言特点
python
刘立军1 天前
使用pyHugeGraph查询HugeGraph图数据
python·graphql
数据智能老司机1 天前
精通 Python 设计模式——创建型设计模式
python·设计模式·架构
数据智能老司机1 天前
精通 Python 设计模式——SOLID 原则
python·设计模式·架构
c8i1 天前
django中的FBV 和 CBV
python·django
c8i1 天前
python中的闭包和装饰器
python
这里有鱼汤1 天前
小白必看:QMT里的miniQMT入门教程
后端·python