定时调度模块:sched
"""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 delayfunctions"""self._queue = []self.timefunc = timefuncself.delayfunc = delayfuncdef 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 IDdef 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() + delayreturn 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._queuedef run(self):"""Execute events until the queue is empty.'''开始执行事件知道队列为空'''When there is a positive delay until the first event, thedelay 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 actionfunction to modify the queue or to raise an exception;延时和动作函数都可以修改事件队列,也可以引发异常exceptions are not caught but the scheduler's state remainswell-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, toavoid monopolizing the CPU when other threads are alsorunnable.允许其他线程运行的一个奇妙的方式是:在执行一个事件之后,执行0s的延时,以避免有其他可运行的线程时,它独占CPU时间"""# localize variable access to minimize overhead# 本地化变量, 以最小化开销# and to improve thread safetyq = self._queuedelayfunc = self.delayfunctimefunc = self.timefuncpop = heapq.heappopwhile 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 runelse:heapq.heappush(q, event)@propertydef 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()

  

posted on 2016-12-15 17:23 桑海 阅读(...) 评论(...) 编辑 收藏

转载于:https://www.cnblogs.com/sanghai/p/6184081.html

定时调度模块:sched相关推荐

  1. 大型云原生项目在数字化企业落地过程解密

    当前,随着互联网的高速发展,各企业的业务量出现几何级增长趋势.越来越多企业发现,使用传统模式部署及运营的产品越来越难以适应新模式下的要求,运维工作越发难以推进.如何搭建一套能够满足子系统高效调度,系统 ...

  2. 【Python】SQLAlchemy长时间未请求,数据库连接断开的原因、解决方案

    这个问题好像和长时间连接数据库但不打开网页时,报错lost connection是一个原因 问题: 写了一个基于apscheduler的定时任务,里面的任务使用了sqlalchemy,大致如下: sc ...

  3. python office库_python库编程.os平台.office平台

    1.库安装 Python库  PyPI – Python Package Index :https://pypi.python.org/ (1) Python库的自定义安装:找到库所在网站,根据指示下 ...

  4. 大型云原生项目在数字化企业落地过程解密 1

    当前,随着互联网的高速发展,各企业的业务量出现几何级增长趋势.越来越多企业发现,使用传统模式部署及运营的产品越来越难以适应新模式下的要求,运维工作越发难以推进.如何搭建一套能够满足子系统高效调度,系统 ...

  5. 基于Linux的集群系统(五) Linux集群系统的实现

    1.设计目标 设计一个基于Linux的集群系统,它能够提供负载平衡的功能.系统能够不断监视集群中各台实际服务器的负载状况,并且将来自外部网的多种请求转发到内部网中的某一台实际服务器上执行. 具体来说, ...

  6. python使用微信推送消息

    python使用微信推送消息 from wxpy import * #该库主要是用来模拟与对接微信操作的 import requests from datetime import datetime i ...

  7. 爬取微博实时热搜数据可视化分析

    文章目录 爬取微博实时热搜数据可视化分析 一.爬取数据 1.1 Spider主要函数 1.2 根据微博一分钟更新一次的状态进行爬虫 二.可视化 2.1 利用轮播图加柱状图进行可视化 爬取微博实时热搜数 ...

  8. python timer 死掉_Python定时事件 Timer sched

    我们经常需要定时的执行某一个任务,在C/C++ 等语言中我们可以使用定时器,但是在Python中,标准库给我们提供了两种方式Timer和Sched. 先说sched模块,准确的说,它是一个调度(延时处 ...

  9. 周期性/定时执行python任务,使用三种方法:while、apscheduler、sched

    文章目录 方法一:使用while关键字 方法二:使用apscheduler第三方库 方法三:使用源生sched做循环的任务 首先写一个main函数: import sys import os from ...

最新文章

  1. java程序中日志jar包的使用_java – 如何使用jar文件中的Liquibase changelog
  2. IT人的学习方法论-续集 关于英语的学习
  3. 第二十五章补充内容 3 assert()宏
  4. 第五周课程总结试验报告(三)
  5. vant引入组件报错_强烈推荐优秀的Vue UI组件库
  6. [机器学习]正则化项L1和L2的学习与理解
  7. URLEncoder URLDecoder
  8. Chrome浏览器打开Axure原型图
  9. 影响力最大化——CELF算法的简介与python实现
  10. html5微信 红包源码,微信抢红包源码和模拟demo
  11. hdu 3786 找出直系亲属 (DFS)
  12. ValueError: y contains previously unseen labels: ‘103125‘
  13. 推荐21款最佳 HTML5 网页游戏
  14. 技术书写作你要知道的几件事
  15. 湘南巷子商城“0元购”逆袭上线
  16. 2021年国企、银行求职面经汇总(更新中)
  17. Anaconda下安装Tensorflow和Keras的安装教程
  18. 如何进行SYN攻击防范
  19. 免激活Vista并合法使用1年的方法
  20. 5G(2)5G NR Redcap

热门文章

  1. PHP中魔术方法的用法
  2. PHP feof() 函数读文件的使用
  3. Vml+Dhtml:制作一个应用渐变颜色效果不错的进度条
  4. ASP.NET重用代码技术 - 代码绑定技术
  5. XML的简单读取与写入
  6. PE文件和COFF文件格式分析——导出表
  7. C++11中std::condition_variable的使用
  8. Python处理XML文件
  9. html在页面上div绝对定位,html – 中心浮动div在绝对定位div内
  10. c语言函数调用编译等腰三角形,C语言如何输出带“*”的等腰三角形? – 手机爱问...