当前位置: 首页 > 编程日记 > 正文

定时调度模块:sched

定时调度模块: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

相关文章:

Mat转换为IplImage 类型和CvMat 类型

cv::Mat img; CvMat cvMatImg img; IplImage IplImg img;转载&#xff1a;http://blog.csdn.net/zhuwei1988

大数据学习思路

学习大数据已经有一段时间了&#xff0c;抽空回顾一下自己学习的一些内容。下图主要为自己学习大数据的一个过程。 阶段一&#xff1a;Java基础 掌握JAVA基本语法、面向对象、集合、IO流、多线程、网络编程 阶段二&#xff1a;MySQL CRUD 阶段三&#xf…

【C++】【十二】排序实现及思路

掌握核心知识点&#xff1a; 1.插入排序在一下2种情况效率较高&#xff1a;1&#xff09;数据基本有序 2&#xff09;数据序列较少 希尔排序是在插入排序的基础上的改进。 2.快速排序 3.归并排序 4.堆排序&#xff1a;数据初始化为数据&#xff0c;根据完全二叉树&#…

Centos 不小心删除了openssl,导致无法使用sshd、yum、wget、curl 等软件的问题。。...

2019独角兽企业重金招聘Python工程师标准>>> 1、如果安装了FTP&#xff0c;可以使用FTP上传rpm到服务器进行安装&#xff1b; 2、挂载光驱cdrom到mnt文件夹下&#xff0c;进入package文件夹rpm进行安装&#xff1b; 3、有源码包进行源码安装&#xff1b; 4、自求多福…

IplImage 类型和 CvMat 类型转换为 Mat 类型

IplImage *IplImg cvLoadImage("fruits.jpg"); Mat img(IplImg, true);转载&#xff1a;http://blog.csdn.net/zhuwei1988

麦当劳数字化转型中获得的6个数据科学经验

摘要 美国大数据公司Civis Analytics于2017年底与麦当劳北美市场营销和数据科学团队建立了数据技术合作伙伴关系&#xff0c;经过一年半的努力&#xff0c;近期在纽约广告周上共同展示了一些重要的学习成果。 麦当劳客户数据科学总监David Galinsky和麦当劳媒体科学经理Emma Hi…

操作系统(三)

学习记录&#xff08;3&#xff09; 线程 1.线程的优势在哪&#xff1f; 1.1 多线程之间会共享同一块地址空间和所有可用数据的能力&#xff0c;这是进程所不具备的。 1.2 线程要比进程更轻量级&#xff0c;由于线程更轻&#xff0c;所以它比进程更容易创建&#xff0c;也更容…

【Kubernetes】两篇文章 搞懂 K8s 的 fannel 网络原理

近期公司的flannel网络很不稳定&#xff0c;花时间研究了下并且保证云端自动部署的网络能够正常work。 1.网络拓扑 拓扑如下&#xff1a;&#xff08;点开看大图&#xff09; 容器网卡通过docker0桥接到flannel0网卡&#xff0c;而每个host对应的flannel0网段为 10.1.x.[1-255…

图像读取、转为灰度图像、均值平滑、显示保存操作

#include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <iostream> int main( ) {// 读取图像源cv::Mat srcImage cv::imread("..\\images\\pool.jpg");if( srcImage…

python 查询 elasticsearch 常用方法(Query DSL)

2019独角兽企业重金招聘Python工程师标准>>> 1. 建立连接 from elasticsearch import Elasticsearch es Elasticsearch(["localhost:9200"])2. 查询所有数据 # 方式1&#xff1a; es.search(index"index_name", doc_type"type_name"…

OpenCV 【十一】—— 图像去畸变,对极约束之undistort,initUndistortRectifyMap,undistort

目录 0.极限约束&#xff0c;对极校正 1.摄像机成像原理简述 2.成像畸变 2.1. 畸变数学模型 2.2. 公式推导 3.畸变校正 3.1. 理论推导 4. 图像去畸变** 5. 图像尺度缩放与内参的关系** 5.1 undistortPoints() 5.2 initUndistortRectifyMap() 5.3 undistort() 6.Un…

Ubuntu14.04 Mininet中将Openvswitch升级步骤

2019独角兽企业重金招聘Python工程师标准>>> 首先下载Mininet apt-get install mininetservice openvswitch-controller stopupdate-rc.d openvswitch-controller disablemn --test pingall 这里可能会出现以下错误sudo mn --mac --controllerremote,port6653 --top…

(转)软件测试的分类软件测试生命周期

软件测试的分类&软件测试生命周期 软件测试的分类&#xff1a; 按测试执行阶段&#xff1a;单元测试、集成测试、系统测试、验收测试、&#xff08;正式验收测试&#xff0c;Alpha 测试-内侧&#xff0c;Beta 测试-公测&#xff09; 按测试技术分类&#xff1a;黑盒测试、白…

OpenCV 【十二】OpenCV如何扫描图像、利用查找表和计时

目录 OpenCV如何扫描图像、利用查找表和计时 1.函数计算时间测试case 2. Mat图像的存储机理 3. 像素遍历的3--4种方式 4. 实例 OpenCV如何扫描图像、利用查找表和计时 如何计算函数运行时间&#xff1f; Mat图像如何存储&#xff1f; 如何高效遍历图像像素&#xff1f; …

Java String.split()用法小结

2019独角兽企业重金招聘Python工程师标准>>> 在java.lang包中有String.split()方法,返回是一个数组 我在应用中用到一些,给大家总结一下,仅供大家参考: 1、如果用“.”作为分隔的话,必须是如下写法,String.split("\\."),这样才能正确的分隔开,不能用Strin…

217. 验证码 demo

2019独角兽企业重金招聘Python工程师标准>>> 1.效果 2.准备&#xff1a; 下载相关的jar 这里我使用的是ValidateCode 这个jar https://my.oschina.net/springMVCAndspring/blog/1815719 &#xff08;1&#xff09;相关jar下载路径 链接&#xff1a;https://pan.…

OpenCV 【十三】矩阵的掩码操作

目录 1 Mask掩膜/滤波核 1.1 原理 1.2 实例 1.3 结果对比 2. filter2D函数 2.1 原理 2.2 实例 2.3 结果 1 Mask掩膜/滤波核 1.1 原理 矩阵的掩码操作很简单。其思想是&#xff1a;根据掩码矩阵&#xff08;也称作核&#xff09;重新计算图像中每个像素的值。掩码矩阵中…

【ArrayList】为什么java.util.concurrent 包里没有并发的ArrayList实现?

2019独角兽企业重金招聘Python工程师标准>>> 为什么java.util.concurrent 包里没有并发的ArrayList实现&#xff1f; 问&#xff1a;JDK 5在java.util.concurrent里引入了ConcurrentHashMap&#xff0c;在需要支持高并发的场景&#xff0c;我们可以使用它代替HashMa…

Android实现买卖商品小游戏

之前为了学习GreenDao&#xff0c;写的练手项目&#xff0c;欢迎指点 仿手游《混》《买房记》&#xff0c;单机游戏&#xff0c;无需联网 1、主界面 2、游戏界面 可以选择地区出发随机事件&#xff0c;进行贷款/还款&#xff0c;治疗&#xff0c;还债&#xff0c;买卖商品&…

OpenCV 【十四】改变图像的对比度和亮度高度关联章节:OpenCV 【十】——Gamma校正 ——图像灰度变化

目录 0 提问 1.1 原理 trick: 1.2 代码 1.3 结果 0 提问 访问像素值 用0初始化矩阵 saturate_cast 是做什么用的&#xff0c;以及它为什么有用 1.1 原理 图像处理 一般来说&#xff0c;图像处理算子是带有一幅或多幅输入图像、产生一幅输出图像的函数。 图像变换可分…

getRotationMatrix2D 函数

cv::Mat cv::getRotationMatrix2D( Point2f center, double angle, double scale ) {// 角度转换angle * CV_PI/180;// 计算旋转矩阵角度double alpha cos(angle)*scale;double beta sin(angle)*scale;Mat M(2, 3, CV_64F);double* m (double*)M.data;// 构建旋转矩阵m[0] …

java学习笔记-java中运算符号的优先顺序

java中各种运算符具有优先级顺序&#xff0c;一般会先计算优先级高的&#xff0c;再计算优先级低的。可以使用()使得优先级变为最高。在算术运算中&#xff0c;优先级为 --* &#xff0f; -在在逻辑运算中的优先级是 ! 取反&& || & |在位运算中的优先级 &#xff…

红帽发布第四季度和2019财年报告,多项指标维持两位数增速

近日&#xff0c;红帽公司发布了其第四季度和2019财年报告。这是在被 IBM以340亿美元的价格收购 后&#xff0c;红帽公布的第一份财报&#xff0c;数据颇为亮眼。 报告显示&#xff0c;红帽公司第四季度总收入8.79亿美元&#xff0c;同比增长14%&#xff1b;整个财年营收34亿美…

OpenCV 【十五】绘直线/椭圆/矩形/圆及其填充

目录 1. 概况 2. 原理 2.1 Point 2.2 Scalar 3. 代码 4.结果 1. 概况 如何用 Point 在图像中定义 2D 点 如何以及为何使用 Scalar 用OpenCV的函数 line 绘 直线 用OpenCV的函数 ellipse 绘 椭圆 用OpenCV的函数 rectangle 绘 矩形 用OpenCV的函数 circle 绘 圆 用Op…

spring-boot Junit4单元测试

2019独角兽企业重金招聘Python工程师标准>>> 如果是使用spring-boot 1.4以下的版本 RunWith(SpringJUnit4ClassRunner.class) SpringApplicationConfiguration(classes 启动类.class) public class ApplicationTest {//代码省略 } 使用SpringApplicationConfigurat…

VideoCapture 读取视频文件,显示视频(帧)信息

#include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <iostream> using namespace std; using namespace cv; int main() {// 定义相关VideoCapture对象VideoCapture capture;…

Go 1.12发布:改进了运行时性能以及模块支持

Go最新版本1.12于近日发布&#xff0c;该版本并没有改动语法规范&#xff0c;它主要对运行时性能、编译工具链以及模块系统等进行了优化。另外&#xff0c;它还为TLS 1.3提供了opt-in支持&#xff0c;同时改进了对MacOS和iOS等系统的支持。 Go 1.12最大的更新亮点是改进了Go运行…

OpenCV 【十六】RNG随机数发生器putText绘制文字

1 目的 使用 随机数发生器类 (RNG) 并得到均匀分布的随机数。 通过使用函数 putText 显示文字。 第一步是实例化一个 Random Number Generator&#xff08;随机数发生器对象&#xff09; (RNG): RNG rng( 0xFFFFFFFF ); 初始化一个 0 矩阵(代表一个全黑的图像), 并且指定它…

分享一段Java搞笑的代码注释

原文&#xff1a;http://www.cnblogs.com/xdp-gacl/p/4198935.html // _ooOoo_ // o8888888o // 88" . "88 // (| -_- |) // …

视频写操作,通道分离与合并

#include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <iostream> using namespace std; using namespace cv; int main() { // 视频读入与输出路径设置 string sourceVideoPath "..\\images\\test.avi"; st…