use mutex to lock scheduler
This commit is contained in:
parent
41317e5029
commit
ba8d0921bb
1 changed files with 15 additions and 11 deletions
|
|
@ -17,7 +17,7 @@
|
||||||
|
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
from threading import Timer, Event
|
from threading import Timer, Event, RLock
|
||||||
|
|
||||||
|
|
||||||
__all__ = ['Scheduler']
|
__all__ = ['Scheduler']
|
||||||
|
|
@ -38,6 +38,7 @@ class IScheduler(object):
|
||||||
|
|
||||||
class Scheduler(IScheduler):
|
class Scheduler(IScheduler):
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
|
self.mutex = RLock()
|
||||||
self.stop_event = Event()
|
self.stop_event = Event()
|
||||||
self.count = 0
|
self.count = 0
|
||||||
self.queue = {}
|
self.queue = {}
|
||||||
|
|
@ -46,15 +47,17 @@ class Scheduler(IScheduler):
|
||||||
if self.stop_event.isSet():
|
if self.stop_event.isSet():
|
||||||
return
|
return
|
||||||
|
|
||||||
self.count += 1
|
with self.mutex:
|
||||||
logging.debug('function "%s" will be called in %s seconds' % (function.__name__, interval))
|
self.count += 1
|
||||||
timer = Timer(interval, self._callback, (self.count, function, args))
|
logging.debug('function "%s" will be called in %s seconds' % (function.__name__, interval))
|
||||||
self.queue[self.count] = timer
|
timer = Timer(interval, self._callback, (self.count, function, args))
|
||||||
timer.start()
|
self.queue[self.count] = timer
|
||||||
return self.count
|
timer.start()
|
||||||
|
return self.count
|
||||||
|
|
||||||
def _callback(self, count, function, args):
|
def _callback(self, count, function, args):
|
||||||
self.queue.pop(count)
|
with self.mutex:
|
||||||
|
self.queue.pop(count)
|
||||||
return function(*args)
|
return function(*args)
|
||||||
|
|
||||||
def repeat(self, interval, function, *args):
|
def repeat(self, interval, function, *args):
|
||||||
|
|
@ -65,9 +68,10 @@ class Scheduler(IScheduler):
|
||||||
|
|
||||||
def _wait_to_stop(self):
|
def _wait_to_stop(self):
|
||||||
self.want_stop()
|
self.want_stop()
|
||||||
for e in self.queue.itervalues():
|
with self.mutex:
|
||||||
e.cancel()
|
for e in self.queue.itervalues():
|
||||||
e.join()
|
e.cancel()
|
||||||
|
e.join()
|
||||||
|
|
||||||
def run(self):
|
def run(self):
|
||||||
try:
|
try:
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue