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()
相关推荐
@zulnger1 分钟前
python 学习笔记(闭包)
笔记·python·学习
SHolmes18542 分钟前
Python all函数 判断是否同时满足多个条件
java·服务器·python
inksci2 分钟前
Python 中使用 SQL 连接池
服务器·数据库·python
子午6 分钟前
【2026原创】中草药识别系统实现~Python+深度学习+模型训练+人工智能
人工智能·python·深度学习
洛克大航海7 分钟前
Python 在系统 Windows 和 Ubuntu 中创建虚拟环境
windows·python·ubuntu·虚拟环境
ZEERO~9 分钟前
@dataclass的作用
开发语言·windows·python
南行*16 分钟前
C语言Linux环境编程
linux·c语言·开发语言·网络安全
Morwit18 分钟前
Qt qml创建c++类的单例对象
开发语言·c++·qt
几道之旅19 分钟前
pytdx能否下载期货数据呢?
python
古城小栈21 分钟前
Rust 已经自举,却仍需GNU与MSVC工具链的缘由
开发语言·rust