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()
相关推荐
white-persist4 分钟前
差异功能定位解析:C语言与C++(区别在哪里?)
java·c语言·开发语言·网络·c++·安全·信息可视化
q***72875 分钟前
Golang 构建学习
开发语言·学习·golang
hmbbcsm12 分钟前
练习python题目小记(五)
开发语言·python
蓝桉~MLGT13 分钟前
Python学习历程——文件
python·学习·策略模式
循环过三天14 分钟前
7.5、Python-匿名函数lambda
笔记·python·学习
kokunka17 分钟前
C#类修饰符功能与范围详解
java·开发语言·c#
仟濹28 分钟前
【Java 基础】3 面向对象 - this
java·开发语言·python
Dxy123931021634 分钟前
Python一个类的特殊方法有哪些
开发语言·python
爱吃烤鸡翅的酸菜鱼42 分钟前
如何用【rust】做一个命令行版的电子辞典
开发语言·rust