网络编程
位置:首页>> 网络编程>> Python编程>> python定时任务sched库用法简单实例

python定时任务sched库用法简单实例

作者:IT之一小佬  发布时间:2023-11-07 07:26:14 

标签:python,定时任务,sched

前言

sched是Python的内置模块,用于事件调度,可在安全的在多线程环境中轻松实现定时任务。

sched是一种调度(延时处理机制)。

sched是python内置库,不需要安装。

示例代码:

import sched
import time
from datetime import datetime

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

def task(inc):
   now = datetime.now()
   ts = now.strftime("%Y-%m-%d %H:%M:%S")
   print(ts)
   schedule.enter(inc, 0, task, (inc,))

def func(inc=3):
   # enter四个参数分别为:
   # 间隔事件、优先级(用于同时间到达的两个事件同时执行时定序)、被调用触发的函数、给该触发函数的参数(tuple形式)
   schedule.enter(0, 0, task, (inc,))
   schedule.run()

func()

运行结果:

python定时任务sched库用法简单实例

补充:解析

主要使用调度器对象 sched.scheduler

调度器对象初始化方法 def __init__(self, timefunc=_time, delayfunc=time.sleep)

  • timefunc:经过时间调用的方法,默认为 time.monotonic(),返回单调时钟的值,单位为小数秒

  • delayfunc:延迟时间调用的方法,默认为 time.sleep(secs),线程暂停执行secs秒

调度器对象方法和属性有:

方法或属性功能
scheduler.enterabs(time, priority, action, argument=(), kwargs={})安排一个新事件
scheduler.enter(delay, priority, action, argument=(), kwargs={})安排延后 delay 时间单位的事件
scheduler.cancel(event)从队列中删除事件
scheduler.empty()判断事件队列是否为空
scheduler.run(blocking=True)运行所有预定事件
scheduler.queue按运行顺序返回事件列表

总结 

来源:https://blog.csdn.net/weixin_44799217/article/details/127353545

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com