栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python笔记15--常见定时功能

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python笔记15--常见定时功能

python笔记15--常见定时功能
  • 1 简介
  • 2 定时方法
    • 最粗暴的 while+sleep
    • schedule 实现定时
    • APScheduler 后台定时
  • 3 注意事项
  • 4 说明

1 简介

实际项目中经常要执行一些定时任务,因此有必要按需选择一些定时方法。本文列举出一些常见的定时方法,加上测试代码和优缺点分析; 分享在此处以便于有需要的小伙伴查阅学习,后续会再此处续更定时相关的功能。

2 定时方法 最粗暴的 while+sleep

最简单的方式可以通过while 循环, 每 sleep ts时间后执行制定任务。
优点:简单
缺点:不适合后台定时,处理函数太久会造成定时不准确。

import datetime
import time


def print_time(cron_type):
    ts = int(time.time())
    print("{},{},{}".format(ts, datetime.datetime.now().strftime('%Y-%m-%dT%H:%M:%S+0800'), cron_type))
    time.sleep(6)
    print("{},{},{}, add 1s".format(ts, datetime.datetime.now().strftime('%Y-%m-%dT%H:%M:%S+0800'), cron_type))


def test_cron_v1(ts=10):
    while True:
        print_time("v1")
        time.sleep(ts)
schedule 实现定时

使用schedule的库实现多样化定时。需要安装 schedule 库 pip3 install schedule
优点:简单,定时类型多样
缺点:不适合后台定时

import schedule
import datetime
import time


def print_time(cron_type):
    ts = int(time.time())
    print("{},{},{}".format(ts, datetime.datetime.now().strftime('%Y-%m-%dT%H:%M:%S+0800'), cron_type))
    time.sleep(6)
    print("{},{},{}, add 1s".format(ts, datetime.datetime.now().strftime('%Y-%m-%dT%H:%M:%S+0800'), cron_type))


def test_cron_v3(ts=10):
    schedule.every(ts).seconds.do(print_time, cron_type="v3")
    # schedule.every().minute.at(":10").do(print_time, cron_type="v3")
    while True:
        schedule.run_pending()
APScheduler 后台定时

使用APScheduler 实现多样化定时。需要安装APScheduler库 pip3 install APScheduler
优点: 比较方便后台定时,类型多样
缺点: 比上面两种方法稍微复杂一点

"""Basic Flask Example."""
import datetime

from flask import Flask

from apscheduler.schedulers.background import BackgroundScheduler


app = Flask(__name__)


def job1():
    print(datetime.datetime.now())


@app.route('/')
def test_scheduler():
    return 'hello, scheduler'


if __name__ == "__main__":
    scheduler = BackgroundScheduler()
    # 添加任务,间隔5s执行一次func()函数
    scheduler.add_job(func=job1, trigger="interval", seconds=5)
    # 启动定时器
    scheduler.start()
    app.run()
3 注意事项
  1. to add
4 说明

软件环境:
python 3.9
APScheduler (pip 安装)

参考文档:
schedule.readthedocs.io
Python: 定时任务的实现方式, Crontab 任务, 定时运行

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/339302.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号