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()
相关推荐
暮冬-  Gentle°1 小时前
C++中的命令模式实战
开发语言·c++·算法
勾股导航2 小时前
大模型Skill
人工智能·python·机器学习
2501_945423543 小时前
Django全栈开发入门:构建一个博客系统
jvm·数据库·python
FreakStudio4 小时前
保姆级 uPyPi 教程|从 0 到 1:MicroPython 驱动包一键安装 + 分享全攻略
python·嵌入式·电子diy
Volunteer Technology4 小时前
架构面试题(一)
开发语言·架构·php
清水白石0084 小时前
Python 对象序列化深度解析:pickle、JSON 与自定义协议的取舍之道
开发语言·python·json
2401_876907524 小时前
Python机器学习实践指南
开发语言·python·机器学习
努力中的编程者5 小时前
栈和队列(C语言底层实现环形队列)
c语言·开发语言
张张123y5 小时前
RAG从0到1学习:技术架构、项目实践与面试指南
人工智能·python·学习·面试·架构·langchain·transformer