Python 中高级知识 sched

sched

sched 模块定义了一个实现通用事件调度程序的类。专用于计划任务的执行

目前sched的模型很简单,就一个相对延迟任务和一个绝对时间点任务

样例

# !/usr/bin/env python3
# -*- coding: utf-8 -*
 
 
import sched
import time
 
# 生成调度器
s = sched.scheduler(time.time, time.sleep)
 
 
def print_time(a='default'):
    print("From print_time", time.time(), a)
 
 
def print_some_times():
    print(time.time())
    # 加入调度事件
    s.enter(101, print_time)  # default
    # 四个参数分别是:
    # 间隔时间(具体值决定与delayfunc, 这里为秒);
    # 优先级(两个事件在同一时间到达的情况);
    # 触发的函数;
    # 函数参数
    s.enter(52, print_time, argument=('positional',))  # positional
    s.enter(51, print_time, kwargs={'a''keyword'})  # keyword
    # 运行调度
    s.run()
    print(time.time())
 
 
print_some_times()

运行结果:先打印keyword,因为时间5秒,级别1高,然后是5秒级别2的positional,最后才是10秒的default

1576740481.8870814
From print_time 1576740486.8873906 keyword
From print_time 1576740486.8873906 positional
From print_time 1576740491.888005 default
1576740491.888005

在多线程场景中,会有线程安全问题,run()函数会阻塞主线程。

Each instance of this class manages its own queue. No multi-threading is implied; you are supposed to hack that yourself, or use a single instance per application.

sched 并不是多线程安全的,每个sched实例有自己维护的队列,但是在多线程场景下有并发修改问题。如果你需要做到了线程安全,要么你使用单例模式或者你自己做线程同步

官方文档:https://docs.python.org/zh-cn/3.7/library/sched.html

略微注意下,sched.scheduler(timefunc=time.monotonic, delayfunc=time.sleep) 这两个入参都是函数,其中timefunc是一个返回不变时间点的函数,用来做后续的定时任务的时间参考点,在时间参考点和实际延迟任务的时间点之间,sched是不需要做任何事情的,这时需要给一个这个空闲时间段内的操作,一般是主动的线程休眠或者让出线程时间片。一般默认就是sleep

timefunc 以前是需要给的,在python3.3中,有了默认值,具体请看代码,默认值是time模块里面的_time,作用也是不可变的时间点

delayfunc 以前也是需要给的,在python3.3中,有了默认值,默认是time.sleep

其实sched功能还是很单调,时间使用的时候也许我们还是习惯使用cron表达式,那么这个就不适合了,可能需要第三方库。sched只是一个延时队列,模型也简单

 

 
posted @ 2021-09-26 10:43  旁人X  阅读(575)  评论(0)    收藏  举报