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

Python 定时任务

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

Python 定时任务

1、sleep

from datetime import datetime
import time

# 每n秒执行一次
def timer(n):
    while True:
        print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
        time.sleep(n)
# 5s
timer(5)

2、threading模块中的Timer

from datetime import datetime
from threading import Timer

# 打印时间函数
def printTime(inc):
    print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
    t = Timer(inc, printTime, (inc,))
    t.start()
# 5s
printTime(5)

3、sched模块

import sched
import time
from datetime import datetime

# 初始化sched模块的 scheduler 类,生成调度器
# 第一个参数是一个可以返回时间戳的函数,第二个参数可以在定时未到达之前阻塞。
schedule = sched.scheduler(time.time, time.sleep)

# 被周期性调度触发的函数
def printTime(inc):
    print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
    schedule.enter(inc, 0, printTime, (inc,))

# 默认参数60s
def main(inc=60):
    # enter四个参数分别为:间隔事件、优先级(用于同时间到达的两个事件同时执行时定序)、被调用触发的函数,加入调度事件
    # 给该触发函数的参数(tuple形式)
    schedule.enter(0, 0, printTime, (inc,))
    schedule.run()
# 10s 输出一次
main(10)

4、APScheduler定时框架
APScheduler 四个组件分别为:
触发器(trigger)
作业存储(job store)
执行器(executor)
调度器(scheduler)

APScheduler 安装

pip install apscheduler

*
*
*
*
*
*
*
*

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

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

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