"""A generally useful event scheduler class.
事件调度器类 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.
'不隐含多线程,你应该自己实现它或者每个应用程序使用单独一个实例' Each instance is parametrized with two functions, one that is
supposed to return the current time, one that is supposed to
implement a delay.
'每个实例都用两个函数参数,一个函数返回当前时间,一个函数参数实现延时'
You can implement real-time scheduling by
substituting time and sleep from built-in module time, or you can
implement simulated time by writing your own functions.
'你可以通过替换内置时间模块的时间和休眠来实现实时调度,也可以一个通过编写自己的函数来实现模拟时间'
This can also be used to integrate scheduling with STDWIN events;
'也可以用于整合stdwin事件调度'
the delay function is allowed to modify the queue. Time can be expressed as
integers or floating point numbers, as long as it is consistent.
'允许延时函数修队列. 时间可以表示为整数或浮点数,只要它是一致的' Events are specified by tuples (time, priority, action, argument).
'事件是指定为(时间、优先级、动作、参数)的元组'
As in UNIX, lower priority numbers mean higher priority;
'在UNIX中,较小的数意味着更高的权限'
in this way the queue can be maintained as a priority queue.
以这种方式,维护一个优先队列
Execution of the event means calling the action function, passing it the argument
执行事件,意味着调用动作函数, 将参数序列argument 传递给它
sequence in "argument" (remember that in Python, multiple function
arguments are be packed in a sequence).
在python中,多个函数参数被打包在一个元组中
The action function may be an instance method so it
has another way to reference private data (besides global variables).
动作函数可能是一个实例方法,所以它有另一种引用私有变量(除了全局变量)的方式
""" # XXX The timefunc and delayfunc should have been defined as methods
# XXX so you can define new kinds of schedulers using subclassing
# XXX instead of having to define a module or class just to hold
# XXX the global state of your particular time and delay functions. import heapq
from collections import namedtuple __all__ = ["scheduler"] Event = namedtuple('Event', 'time, priority, action, argument') class scheduler:
def __init__(self, timefunc, delayfunc):
"""Initialize a new instance, passing the time and delay
functions"""
self._queue = []
self.timefunc = timefunc
self.delayfunc = delayfunc def enterabs(self, time, priority, action, argument):
"""Enter a new event in the queue at an absolute time. Returns an ID for the event which can be used to remove it,
if necessary. """
event = Event(time, priority, action, argument)
heapq.heappush(self._queue, event)
return event # The ID def enter(self, delay, priority, action, argument):
"""A variant that specifies the time as a relative time. This is actually the more commonly used interface. """
time = self.timefunc() + delay
return self.enterabs(time, priority, action, argument) def cancel(self, event):
"""Remove an event from the queue. This must be presented the ID as returned by enter().
If the event is not in the queue, this raises ValueError. """
self._queue.remove(event)
heapq.heapify(self._queue) def empty(self):
"""Check whether the queue is empty."""
return not self._queue def run(self):
"""Execute events until the queue is empty.
'''开始执行事件知道队列为空''' When there is a positive delay until the first event, the
delay function is called and the event is left in the queue;
第一个事件之前,延时为正数, 则调用延时函数,事件留在元队列中
otherwise, the event is removed from the queue and executed
(its action function is called, passing it the argument). If
否则,时间移除队列,并开始执行动作函数,动作函数用argument作为参数
the delay function returns prematurely, it is simply restarted.
如果延时函数过提前返回,则延时函数重新启动 It is legal for both the delay function and the action
function to modify the queue or to raise an exception;
延时和动作函数都可以修改事件队列,也可以引发异常
exceptions are not caught but the scheduler's state remains
well-defined so run() may be called again.
未捕获的异常,但是计划程序状态仍是明确的,所以,run()程序可以再次被调用 A questionable hack is added to allow other threads to run:
just after an event is executed, a delay of 0 is executed, to
avoid monopolizing the CPU when other threads are also
runnable.
允许其他线程运行的一个奇妙的方式是:
在执行一个事件之后,执行0s的延时,以避免有其他可运行的线程时,它独占CPU时间 """
# localize variable access to minimize overhead
# 本地化变量, 以最小化开销
# and to improve thread safety
q = self._queue
delayfunc = self.delayfunc
timefunc = self.timefunc
pop = heapq.heappop
while q:
time, priority, action, argument = checked_event = q[0]
now = timefunc()
if now < time:
delayfunc(time - now)
else:
event = pop(q)
# Verify that the event was not removed or altered
# by another thread after we last looked at q[0].
# 验证我们在最后看到q[0]后, 该时间未被其他线程删除或更改
if event is checked_event:
action(*argument)
delayfunc(0) # Let other threads run
else:
heapq.heappush(q, event) @property
def queue(self):
"""An ordered list of upcoming events.
# 一个即将执行的事件的有序列表 Events are named tuples with fields for:
time, priority, action, arguments """
# Use heapq to sort the queue rather than using 'sorted(self._queue)'.
# With heapq, two events scheduled at the same time will show in
# the actual order they would be retrieved.
events = self._queue[:]
return map(heapq.heappop, [events]*len(events))

  我的练习测试:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
import time, sched def LOG(msg):
print msg def init():
LOG(timenow())
s = sched.scheduler(time.time, time.sleep)
return s def timenow():
return time.time() def show_time(msg):
sec = time.time()
area = time.localtime(sec)
tm = time.asctime(area)
print ''.join(msg)+ tm def to_timestamp():
t = (2016, 12, 15, 16, 34, 50, 0, 0, 0)
return time.mktime(t) def periodic_task(s, delay, priority, periodic_task, action, argument):
LOG(timenow())
action(argument);
s.enter(delay, priority, periodic_task, (s, delay, priority, periodic_task, action, argument)) def do_somethon_before_suicide():
LOG('''it's the time to exit''')
exit() def suicide(s):
s.enterabs(to_timestamp(), 0, do_somethon_before_suicide, ()) def mymain():
s = init() suicide(s)
periodic_task(s, 2, 0, periodic_task, show_time, ('time now is: ', ))
s.run() if __name__ == '__main__':
mymain()

  

定时调度模块:sched的更多相关文章

  1. python 任务调度模块sched

    类似于crontab的功能,可以实现定时定点执行任务; 将已经生成的任务放入队列中,获取到了执行可以实现任务调度功能; 如果将需求复杂化,加上优先级策略,并能取消已经加入队列中的任务,就需要使用pyt ...

  2. 定时器,定时发邮件JavaMail

    一.定时器用法: 1.1先导入jar包 <!--spring整合其他文件时要用的jar包--> <dependency> <groupId>org.springfr ...

  3. python apschedule安装使用与源码分析

    我们的项目中用apschedule作为核心定时调度模块.所以对apschedule进行了一些调查和源码级的分析. 1.为什么选择apschedule? 听信了一句话,apschedule之于pytho ...

  4. 使用node自动生成html并调用cmd命令提交代码到仓库

    生成html提交到git仓库 基于目前的express博客,写了一点代码,通过request模块来请求站点,将html保存到coding-pages目录,复制静态文件夹到coding-pages,最后 ...

  5. Python任务调度模块 – APScheduler

    APScheduler是一个Python定时任务框架,使用起来十分方便.提供了基于日期.固定时间间隔以及crontab类型的任务,并且可以持久化任务.并以daemon方式运行应用.目前最新版本为3.0 ...

  6. C#使用quartz.net定时问题

    因工作需要需要完成定时查询数据..因此在了解之后完成了一个demo 所需要的dll在该地址下载 http://pan.baidu.com/s/1sjNQLXV 首先引入quartz这个dll... 在 ...

  7. java Timer(定时调用、实现固定时间执行)

    最近需要用到定时调用的功能.可以通过java的Timer类来进行定时调用,下面是有关Timer的一些相关知识. 其实就Timer来讲就是一个调度器,而TimerTask呢只是一个实现了run方法的一个 ...

  8. Quartz 定时任务管理

    前言 将项目中的所有定时任务都统一管理吧,使用 quartz 定时任务 设计思路 使用 quartz 的相关jar 包,懒得去升级了,我使用的是 quart 1.6 写一个定时任务管理类 用一张数据库 ...

  9. 用Quartz处理定时执行的任务

    这次做的项目中,有一部分功能需要实现定时执行.呃,这样说可能有点笼统,打个比方吧.例如用户在登录的时候,连续输错3次密码后,系统会将该用户冻结,不再允许该用户登录系统,等到了晚上零晨时分,再为所有被冻 ...

随机推荐

  1. data.table包

    data.table 1.生成一个data.table对象 生成一个data.table对象,记为DT. library(data.table) :],V3=round(rnorm(),),V4=:) ...

  2. NHibernate 中删除数据的几种方法

    今天下午有人在QQ群上问在NHibernate上如何根据条件删除多条数据,于是我自己就写了些测试代码,并总结了一下NHibernate中删除数据的方式,做个备忘.不过不能保证囊括所有的方式,如果还有别 ...

  3. zookeeper清除日志文件工具

    zookeeper运行时间长了以后,日志会成为一个比较大的问题.比如作者压力测试hbase一周以后,zookeeper日志文件达到了10G的规模.由于zookeeper日志文件不能随意删除,因为一个长 ...

  4. float浮动问题:会造成父级元素高度坍塌;

    float浮动问题:会造成父级元素高度坍塌: 解决办法:清除浮动:clear:both; 给父元素高度:height(不是很可取) 给父元素:display:inline-black:(问题:marg ...

  5. ACM spiral grid

    spiral grid 时间限制:2000 ms  |  内存限制:65535 KB 难度:4   描述 Xiaod has recently discovered the grid named &q ...

  6. NOIp 2013 #1 积木大赛 Label:有趣的模拟

    题目描述 春春幼儿园举办了一年一度的“积木大赛”.今年比赛的内容是搭建一座宽度为n的大厦,大厦可以看成由n块宽度为1的积木组成,第i块积木的最终高度需要是hi. 在搭建开始之前,没有任何积木(可以看成 ...

  7. OSG中的HUD

    OSG中的HUD 所谓HUD节点,说白了就是无论三维场景中的内容怎么改变,它都能在屏幕上固定位置显示的节点. 实现要点: 关闭光照,不受场景光照影响,所有内容以同一亮度显示 关闭深度测试 调整渲染顺序 ...

  8. db2日常维护

    一. DB2日常维护操作 1.数据库的启动.停止.激活 db2 list active databases db2 active db 数据库名 db2start --启动 db2stop [forc ...

  9. 修改linux运行级别

    1.Linux下的7个运行级别 0 系统停机模式,系统默认运行级别不能设置为0,否则不能正常启动,机器关闭. 1 单用户模式,root权限,用于系统维护,禁止远程登陆,就像Windows下的安全模式登 ...

  10. C#实现动态页面静态化

    制作一个aspx页面,专门用来生成各个动态aspx页面的静态页面.如下图所示,仅将内容页和主页面生成静态页面,当然本例只是一个简单的范例,实际情况如很复杂,但原理都是相同的. 生成内容页: 本例中的不 ...