本文整理汇总了Python中threading.Timer.stop方法的典型用法代码示例。如果您正苦于以下问题:Python Timer.stop方法的具体用法?Python Timer.stop怎么用?Python Timer.stop使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类threading.Timer
的用法示例。
在下文中一共展示了Timer.stop方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: PeriodicCallback
# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import stop [as 别名]
class PeriodicCallback(object):
"""
A wrapper that uses either `tornado.ioloop.PeriodicCallback` or
`threading.Timer` to call functions at a specified interval depending on
whether or not there's a running instance of `tornado.ioloop.IOLoop`.
.. note::
The purpose of this class is primarily for debugging things in an
interactive Python interpreter. It is expected that in production
you will be using a running `~tornado.ioloop.IOLoop`.
"""
def __init__(self, callback, callback_time, io_loop=None):
self.callback = callback
self.callback_time = callback_time
self.io_loop = io_loop or IOLoop.current()
if self.io_loop._running:
# Use a regular PeriodicCallback
self._pc = PC(callback, callback_time, io_loop)
else:
from threading import Timer
# NOTE: PeriodicCallback uses ms while Timer uses seconds
def callback_wrapper():
"Runs the callback and restarts the Timer so it will run again"
self.callback()
if self._running:
self._pc = Timer(callback_time / 1000, callback_wrapper)
self._pc.start()
self._pc = Timer(callback_time / 1000, callback_wrapper)
self._running = False
def start(self):
"""Starts the timer."""
self._running = True
self._pc.start() # Timer() and PeriodicCallback() both use start()
def stop(self):
"""Stops the timer."""
self._running = False
if isinstance(self._pc, PC): # PeriodicCallback()
self._pc.stop()
else: # Timer()
self._pc.cancel()
示例2: RepeatedTimer
# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import stop [as 别名]
class RepeatedTimer(object):
def __init__(self, interval, function, *args, **kwargs):
self._timer = None
self.interval = interval
self.function = function
self.args = args
self.kwargs = kwargs
def _run(self):
self.function(*self.args, **self.kwargs)
self.start()
def start(self):
self._timer = Timer(self.interval, self._run)
self._timer.start()
# self.is_running = True
def stop(self):
self._timer.cancel()
self._timer.stop()
示例3: RepeatedTimer
# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import stop [as 别名]
class RepeatedTimer(object):
def __init__(self,interval,function):
self.timer = None
self.interval = interval
self.function = function
self.is_running = False
self.start()
def start(self):
if not self.is_running:
self.is_running = True
self.timer = Timer(self.interval,self.run)
self.timer.start()
def run(self):
self.is_running = False
self.function()
self.start()
def stop(self):
self.timer.stop()
self.is_running = False
示例4: ControlCenter
# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import stop [as 别名]
#.........这里部分代码省略.........
# RoboServ output button
button = Tk.Radiobutton( self.outputFrame , text = "[email protected]" , variable = self.outputButtonValue , value = "roboserv" ,
command = self.outputButtonEvent )
button.pack( side = Tk.TOP )
self.outputButton.append( button )
# connect to output button
self.outputConnected = False
self.outputConnectButton = Tk.Button( self.outputFrame , text = "Connect to Output" , command = self.outputConnectButtonPressed )
self.outputConnectButton.pack()
# --------------------------------------------------
# general events
# --------------------------------------------------
# keep alive timer
self.keepAliveTimerPeriod = 1
self.enableKeepAliveTimer()
# event handler for closing window
self.root.protocol( "WM_DELETE_WINDOW" , self.exit )
def exit( self ) :
self.disableKeepAliveTimer()
self.disableJoystick()
self.root.destroy()
try :
self.__roboMote.stopMovement()
self.__roboMote.disableMotors()
except :
pass
#--------------------------------------------------
# Connect to mote or server
#--------------------------------------------------
def connect( self ) :
success = False
while not success :
try :
print "Trying to connect..."
if self.__directConnection :
from Robot import RoboMote
self.__roboMote = RoboMote.RoboMote( self.__connStr )
success = True
else :
from Robot import Client
c = Client.makeClient( host = self.__connStr , ignoreLostPackets = True )
self.__roboMote = c.roboMote
success = True
except :
time.sleep( 10 )
print "Connected"
#--------------------------------------------------
# Keep Alive Timer
#--------------------------------------------------
def enableKeepAliveTimer( self ) :
self.keepAliveTimerActive = True
示例5: EventEngine
# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import stop [as 别名]
class EventEngine(object):
"""
事件驱动引擎
事件驱动引擎中所有的变量都设置为了私有,这是为了防止不小心
从外部修改了这些变量的值或状态,导致bug。
变量说明
__queue:私有变量,事件队列
__active:私有变量,事件引擎开关
__thread:私有变量,事件处理线程
__timer:私有变量,计时器
__handlers:私有变量,事件处理函数字典
方法说明
__run: 私有方法,事件处理线程连续运行用
__process: 私有方法,处理事件,调用注册在引擎中的监听函数
__onTimer:私有方法,计时器固定事件间隔触发后,向事件队列中存入计时器事件
start: 公共方法,启动引擎
stop:公共方法,停止引擎
register:公共方法,向引擎中注册监听函数
unregister:公共方法,向引擎中注销监听函数
put:公共方法,向事件队列中存入新的事件
事件监听函数必须定义为输入参数仅为一个event对象,即:
函数
def func(event)
...
对象方法
def method(self, event)
...
"""
#----------------------------------------------------------------------
def __init__(self):
"""初始化事件引擎"""
# 事件队列
self.__queue = Queue.Queue()
# 事件引擎开关
self.__active = False
# 事件处理线程
self.__thread = Thread(target = self.__run)
# 计时器,用于触发计时器事件
self.__timer = Timer()
self.__timer.timeout.connect(self.__onTimer)
# 这里的__handlers是一个字典,用来保存对应的事件调用关系
# 其中每个键对应的值是一个列表,列表中保存了对该事件进行监听的函数功能
self.__handlers = {}
#----------------------------------------------------------------------
def __run(self):
"""引擎运行"""
while self.__active == True:
try:
event = self.__queue.get(block = True, timeout = 1) # 获取事件的阻塞时间设为1秒
self.__process(event)
except :
pass
#----------------------------------------------------------------------
def __process(self, event):
"""处理事件"""
# 检查是否存在对该事件进行监听的处理函数
if event.type_ in self.__handlers:
# 若存在,则按顺序将事件传递给处理函数执行
[handler(event) for handler in self.__handlers[event.type_]]
# 以上语句为Python列表解析方式的写法,对应的常规循环写法为:
#for handler in self.__handlers[event.type_]:
#handler(event)
#----------------------------------------------------------------------
def __onTimer(self):
"""向事件队列中存入计时器事件"""
# 创建计时器事件
event = Event(type_=EVENT_TIMER)
# 向队列中存入计时器事件
self.put(event)
#----------------------------------------------------------------------
def start(self):
"""引擎启动"""
# 将引擎设为启动
self.__active = True
# 启动事件处理线程
self.__thread.start()
# 启动计时器,计时器事件间隔默认设定为1秒
self.__timer.start(1000)
#.........这里部分代码省略.........
示例6: idlemove
# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import stop [as 别名]
class idlemove(MumoModule):
default_config = {'idlemove':(
('interval', float, 0.1),
('servers', commaSeperatedIntegers, []),
),
lambda x: re.match('(all)|(server_\d+)', x):(
('threshold', commaSeperatedIntegers, [3600]),
('mute', commaSeperatedBool, [True]),
('deafen', commaSeperatedBool, [False]),
('channel', commaSeperatedIntegers, [1]),
('source_channel', commaSeperatedIntegers, [-1]),
('whitelist', commaSeperatedStrings, [])
),
}
def __init__(self, name, manager, configuration=None):
MumoModule.__init__(self, name, manager, configuration)
self.murmur = manager.getMurmurModule()
self.watchdog = None
def connected(self):
self.affectedusers = {} # {serverid:set(sessionids,...)}
manager = self.manager()
log = self.log()
log.debug("Register for Meta & Server callbacks")
cfg = self.cfg()
servers = cfg.idlemove.servers
if not servers:
servers = manager.SERVERS_ALL
manager.subscribeServerCallbacks(self, servers)
manager.subscribeMetaCallbacks(self, servers)
if not self.watchdog:
self.watchdog = Timer(cfg.idlemove.interval, self.handleIdleMove)
self.watchdog.start()
def disconnected(self):
self.affectedusers = {}
if self.watchdog:
self.watchdog.stop()
self.watchdog = None
def handleIdleMove(self):
cfg = self.cfg()
try:
meta = self.manager().getMeta()
if not cfg.idlemove.servers:
servers = meta.getBootedServers()
else:
servers = [meta.getServer(server) for server in cfg.idlemove.servers]
for server in servers:
if not server: continue
if server:
for user in server.getUsers().itervalues():
self.UpdateUserAutoAway(server, user)
finally:
# Renew the timer
self.watchdog = Timer(cfg.idlemove.interval, self.handleIdleMove)
self.watchdog.start()
def UpdateUserAutoAway(self, server, user):
log = self.log()
sid = server.id()
try:
scfg = getattr(self.cfg(), 'server_%d' % sid)
except AttributeError:
scfg = self.cfg().all
try:
index = self.affectedusers[sid]
except KeyError:
self.affectedusers[sid] = set()
index = self.affectedusers[sid]
# Check if the user is whitelisted
if user.name in scfg.whitelist:
return
# Remember values so we can see changes later
threshold = None
mute = user.mute
deafen = user.deaf
channel = user.channel
update = False
over_threshold = False
# Search all our stages top down for a violated treshold and pick the first
for i in range(len(scfg.threshold) - 1, -1, -1):
try:
source_channel = scfg.source_channel[i]
except IndexError:
source_channel = -1
#.........这里部分代码省略.........
示例7: Reader
# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import stop [as 别名]
class Reader():
tcs = False
# The current matched color reading
current = False
# The last color reading
last = False
# Callback for when a new video is found
onNewMedia = False
player = None
timer = None
def __init__(self, onNewMedia=False):
print('Reader: Reader started')
self.onNewMedia = onNewMedia
self.tcs = TCS34725(integrationTime=0xEB, gain=0x01)
self.tcs.setInterrupt(False)
self.player = LoopPlayer( Reader.playlist[0][1] )
self.timer = Timer(1, self._monitor)
self.timer.start()
def _normalize(raw):
denominator = 200
return (
int(raw['r'] / denominator),
int(raw['g'] / denominator),
int(raw['b'] / denominator)
)
def _lookupPlaylistByTuple(t):
for video in Reader.playlist:
if video[0] == t: return video[1]
return False
def _monitor(self):
# print tcs.getRawData()
norm = self._normalize( self.tcs.getRawData() )
print "Reader: norm = " + str(norm)
if( norm != self.last ):
print "Reader: norm = " + str(norm)
self.last = norm
video = self._lookupPlaylistByTuple(norm)
if( video and norm != self.current and video != self.player.filename ):
print "Reader: video = " + str(video)
print(self.onNewMedia)
self.current = norm
# if self.onNewMedia: self.onNewMedia(video)
self.player.stop(exit=False)
self.player = LoopPlayer( video )
self.timer.stop()
self.timer = Timer(0.5, self._monitor)
self.timer.start()
def stop(self):
if(self.timer): self.timer.stop()
self.player.stop
self.tcs.disable()