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()
相关推荐
月走乂山2 小时前
零依赖 GUI:把 OpenCode CLI 变成可视化 AI 任务流水线
python·自动化·ai编程·tkinter·opencode
北冥you鱼2 小时前
Go语言大数(big.Int)比较大小:原理、方法与最佳实践
开发语言·后端·golang
宁之明起(B服)2 小时前
Java 反序列化漏洞-xmldecoder/SnakeYAM
java·开发语言
xcLeigh2 小时前
Go入门:零值与变量默认初始化机制
开发语言·后端·golang
deviant-ART2 小时前
java stream 的 findFirst 及 findAny 方法遇到 null 元素时会出现 NullPointerException
java·开发语言
孙启超3 小时前
【AI应用开发】Agent 无限 loop(反复调用同一个工具)如何规避?
人工智能·python·算法·llm·agent·loop·ai应用开发
银-豆豆3 小时前
Python爬虫
开发语言·爬虫·python
zmzb01033 小时前
C++课后习题训练记录Day179
开发语言·c++
香吧香3 小时前
Python 基础语法总结
python
IT小盘3 小时前
10-使用Reranker提升RAG回答准确率
人工智能·python