码迷,mamicode.com
首页 > 编程语言 > 详细

python标准库之sched 定时事件调度器

时间:2015-03-02 14:43:55      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:

# -*- coding: utf-8 -*-
# 作者:新手
__author__ = ‘Administrator‘
#py标准库之sched
import time
import sched#定时事件调度器
#使用time来掌握当前时间,还有一个是延迟(delay)来指定一个时间段
#调用time是不带任何参数的,返回当前一个时间数,delay要提供一个整数的参数,
#有延迟运行事件
"""
4个方法
1:表示延迟的数;
2:优先级值;
3:要调用的函数;
4:函数参数的元组
"""
#例1:
sche=sched.scheduler(time.time,time.sleep)
def print_event(name,start):
    now=time.time()
    end=int(now-start)
    print ‘event :%s end=%s name=%s‘%(time.ctime(now),end,name)
start=time.time()
print ‘statr:‘,time.ctime(start)
sche.enter(2,1,print_event,(‘first‘,start))#是2秒
sche.enter(3,1,print_event,(‘second‘,start))#3秒
sche.run()
#重叠事件
#run()调用会阻塞,甚至所有事件都已经处理,每个事件都在相同的纯种中运行,所以如果一个事件需要很长时间运行,走出事件之间的延迟,就会出现重叠
#这个重叠可以通过推迟后面的事件来解决,这样一举动丢失事件,不过有些事件可能比其调度时间更晚,
#例2
def longevent(name):
    print ‘1event:‘,time.ctime(time.time()),name
    time.sleep(2)
    print ‘2event‘,time.ctime(time.time()),name
print ‘start‘,time.ctime(time.time())
sche.enter(2,1,longevent,(‘first‘,))
sche.enter(3,1,longevent,(‘second‘,))
sche.run()
#当第一个事件一旦完成就会立即运行第二个事件,因为第一个事件花费的时间比第2个事件长,所以会超过第二个事件的开始时间

#事件优先级
#如果调度多个事件在同一个时间运行,就要使用事优先级来确定它们以何种顺序运行
def yxevent(name):
    print ‘event‘,time.ctime(time.time()),name
now=time.time()
print ‘start:‘,time.ctime(now)
sche.enter(2,1,yxevent,(‘first‘,))
sche.enter(3,1,yxevent,(‘second‘,))
sche.run()

#取消事件
#enter()和enterabs()都会返回一事件一个引用,以后可以用这个引用来取消事件,由于run()阻塞,必须在一个不同线程中取消这个事件
import threading
count=0
def count1(name):
    global  count
    print ‘event‘,time.ctime(time.time()),name
    count+=1
    print ‘now:‘,count
print ‘start:‘,time.ctime(now)
a1=sche.enter(2,1,count1,(‘a1‘,))
a2=sche.enter(3,1,count1,(‘a2‘,))
t=threading.Thread(target=sche.run)
t.start()
sche.cancel(a1)
t.join()
print ‘final:‘,count

#这边调用了2个事件,不过第一个随后被取消,只运行了第二个事件,所以count变量只递增一次

#sched官方标准库:https://docs.python.org/2.7/library/sched.html?highlight=sched#module-sched

 

python标准库之sched 定时事件调度器

标签:

原文地址:http://www.cnblogs.com/mhxy13867806343/p/4308556.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!