flask+apscheduler+ enterprise WeChat message robot push

Introduction : APScheduler is a lightweight Python library for running scheduled and delayed tasks in the background. It can easily schedule tasks and supports many types of triggers, such as fixed intervals, date/time expressions, CRON expressions, etc. APScheduler also provides multiple background scheduler implementations, such as a thread pool-based scheduler, a process pool-based scheduler, and an asynchronous scheduler.

History Raiders:

Python: Celery+Redis+Flower installation and use

Python: Celery+Redis implements timing tasks

Timing tasks: Python

Install dependent libraries:

pip install apscheduler flask

Case source code:

# -*- coding: utf-8 -*-
# time: 2023/4/26 11:25
# file: main.py
# 公众号: 玩转测试开发

from flask import Flask, request
from apscheduler.schedulers.background import BackgroundScheduler
import requests

app = Flask(__name__)


def send_message():
    url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=your-key"
    data = {
    
    
        "msgtype": "text",
        "text": {
    
    "content": "Hello, World!"}
    }
    r = requests.post(url, json=data)


scheduler = BackgroundScheduler()


@app.route("/send_message")
def schedule_message():
    minutes = int(request.args.get("minutes", 1))
    job_id = f"send_message_{
      
      minutes}"
    scheduler.add_job(func=send_message, trigger="interval", minutes=minutes, id=job_id)
    return f"Message scheduled to be sent every {
      
      minutes} minutes with job ID: {
      
      job_id}"


@app.route("/delete_message")
def delete_message():
    job_id = request.args.get("job_id")
    if job_id:
        try:
            scheduler.remove_job(job_id)
            return f"Job {
      
      job_id} deleted."
        except Exception as e:
            return f"Error deleting job {
      
      job_id}: {
      
      e}"
    else:
        return "Please provide a valid job ID."


if __name__ == "__main__":
    scheduler.start()
    app.run(debug=True)

operation result:

picture

Pushed results:

picture

Precautions:

APScheduler是一个后台任务调度库,应该在主线程之外运行。
APScheduler支持多种类型的触发器,例如固定间隔、日期/时间表达式、CRON表达式等。请根据您的需求选择合适的触发器。
如果您需要在多个进程中使用APScheduler,请考虑使用基于数据库的调度器,例如SQLAlchemyJobStore或MongoDBJobStore。
APScheduler提供了许多可自定义的选项和回调函数,例如任务完成时要运行的回调函数。请查看文档以了解更多信息。
为防止任务重复执行,请确保设置唯一的ID参数。

Guess you like

Origin blog.csdn.net/hzblucky1314/article/details/130396335