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()
相关推荐
jimy118 分钟前
readelf 查看“派生类”的vtable符号
开发语言·c++
L@ncor27 分钟前
第二章可能出现的问题
人工智能·python
y = xⁿ35 分钟前
大模型基础概念
python
ctlover1 小时前
排序与查找算法详解
开发语言·python
用户8356290780511 小时前
如何使用 Python 给 Word 文档添加水印
后端·python
YYYing.1 小时前
【C++进阶系列 (七)】C++ RTTI 深度剖析:从 typeid 到 dynamic_cast 的底层之旅
开发语言·c++·c/c++·rtti
泡干脆面就番茄1 小时前
深度学习:PyTorch框架初识——MNIST手写数字识别
python·深度学习
shirsl1 小时前
算法 Day 5 树 / 二叉树 + DFS
数据结构·python·算法
门思科技1 小时前
开源网关有哪些:主流类型梳理
网络·python·物联网
szephyr1 小时前
Python 爬虫合规与反爬实战:从 requests 到 Playwright
爬虫·python·requests·playwright·反爬