监控/定时/scheduler/调度器

发布时间 2023-11-13 02:18:49作者: __username

监控某个玩意更新了,直接上代码了

demo

from flask_apscheduler import APScheduler  # pip install flask-apscheduler
from apscheduler.schedulers.background import BackgroundScheduler
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
# 定义任务
scheduler = BackgroundScheduler()


def send_email(to_email, subject, message, attachment_path=None):
    # 发件人邮箱
    from_email = '你的qq号@qq.com'
    # QQ邮箱授权码
    password = '你的授权码'

    # 邮件设置
    msg = MIMEMultipart()
    msg['From'] = from_email
    msg['To'] = to_email
    msg['Subject'] = subject

    # 邮件正文
    body = MIMEText(message, 'plain')
    msg.attach(body)

    # 添加附件
    if attachment_path:
        attachment = MIMEApplication(open(attachment_path, 'rb').read())
        attachment.add_header('Content-Disposition', 'attachment', filename='attachment_file.txt')
        msg.attach(attachment)

    # 连接到QQ邮件服务器
    with smtplib.SMTP_SSL('smtp.qq.com', 465) as server:
        server.login(from_email, password)
        server.sendmail(from_email, to_email, msg.as_string())


# 定义任务
previous_data = []  # # 假设你有一个变量来存储先前的数据


def my_job():   # 我这里监听微博变化
    # 在这里执行你想要执行的定时任务
    print("定时任务执行了!")
    """+任务"""
    headers = {
        'Accept': 'application/json, text/plain, */*',
        'Accept-Language': 'zh-CN,zh;q=0.9',
        'Cache-Control': 'no-cache',
        'Origin': 'http://43.139.184.232:8080',
        'Pragma': 'no-cache',
        'Proxy-Connection': 'keep-alive',
        'Referer': 'http://43.139.184.232:8080/',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36',
    }

    params = {
        'username1': 'xxxx',
        'page': '1',
    }

    response = requests.get('xxxx/weibo_user_index', params=params, headers=headers, verify=False)

    current_data = response.json()  # (方案2 这里可以直接爬他们的后端接口,而不是调用后端接口)

    # 更新前三个元素
    global previous_data

    # 检查当前数据是否与先前数据不同
    if current_data[:3] != previous_data:
        # 发送邮件示例
        to_email = '给谁的@qq.com'
        subject = 'xxx的主题'
        # message = '你更新了xxx'
        message = str(current_data[0])  # 这里是更新的第一条微博
        send_email(to_email, subject, message)
        # 更新前三个元素
        previous_data = current_data[:3]
    """+结束"""


# 配置定时任务,每1分钟执行一次
scheduler.add_job(my_job, 'interval', minutes=1)

# 将任务绑定到应用
scheduler.start()

配合flask+uwsgi使用