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()
相关推荐
vivo互联网技术13 小时前
ICLR2026 | 视频虚化新突破!Any-to-Bokeh 一键生成电影感连贯效果
人工智能·python·深度学习
敏编程14 小时前
一天一个Python库:virtualenv - 隔离你的Python环境,保持项目整洁
python
喝茶与编码16 小时前
Python异步并发控制:asyncio.gather 与 Semaphore 协同设计解析
后端·python
zone773916 小时前
003:RAG 入门-LangChain 读取图片数据
后端·python·面试
用户83562907805117 小时前
在 PowerPoint 中用 Python 添加和定制形状的完整教程
后端·python
用户9623779544818 小时前
🚀 docx2md-picgo:Word 文档图片一键上传图床工具
python·markdown
zone77392 天前
001:简单 RAG 入门
后端·python·面试
F_Quant2 天前
🚀 Python打包踩坑指南:彻底解决 Nuitka --onefile 配置文件丢失与重启报错问题
python·操作系统
允许部分打工人先富起来2 天前
在node项目中执行python脚本
前端·python·node.js