本文整理汇总了Python中threading.Event.clear方法的典型用法代码示例。如果您正苦于以下问题:Python Event.clear方法的具体用法?Python Event.clear怎么用?Python Event.clear使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类threading.Event
的用法示例。
在下文中一共展示了Event.clear方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: Worker
# 需要导入模块: from threading import Event [as 别名]
# 或者: from threading.Event import clear [as 别名]
class Worker(object):
def __init__(self, jobQueue, secondsPerJob):
self.busyEvent = Event()
self.stopEvent = Event()
def workerFn():
while True:
if self.stopEvent.is_set():
return
try:
jobQueue.get(timeout=1.0)
except Empty:
continue
self.busyEvent.set()
time.sleep(secondsPerJob)
self.busyEvent.clear()
self.startTime = time.time()
self.worker = Thread(target=workerFn)
self.worker.start()
def stop(self):
self.stopEvent.set()
self.worker.join()
return time.time() - self.startTime
示例2: test_term_thread
# 需要导入模块: from threading import Event [as 别名]
# 或者: from threading.Event import clear [as 别名]
def test_term_thread(self):
"""ctx.term should not crash active threads (#139)"""
ctx = self.Context()
evt = Event()
evt.clear()
def block():
s = ctx.socket(zmq.REP)
s.bind_to_random_port('tcp://127.0.0.1')
evt.set()
try:
s.recv()
except zmq.ZMQError as e:
self.assertEqual(e.errno, zmq.ETERM)
return
finally:
s.close()
self.fail("recv should have been interrupted with ETERM")
t = Thread(target=block)
t.start()
evt.wait(1)
self.assertTrue(evt.is_set(), "sync event never fired")
time.sleep(0.01)
ctx.term()
t.join(timeout=1)
self.assertFalse(t.is_alive(), "term should have interrupted s.recv()")
示例3: Dotter
# 需要导入模块: from threading import Event [as 别名]
# 或者: from threading.Event import clear [as 别名]
class Dotter(object):
def __init__(self,delay=100,symbol='.'):
self.event=Event()
self.delay=delay
self.symbol=symbol
self.status=False
def __loop(self):
while not self.event.is_set():
stdout.write(self.symbol)
stdout.flush()
sleep(self.delay/1000)
def start(self):
if not self.status:
self.event.clear()
Thread(target=self.__loop).start()
self.status=True
def stop(self,newLine=True):
if self.status:
self.event.set()
if newLine:
stdout.write('\n')
self.status=False
def set(self,delay=None,symbol=None):
if delay!=None:
self.delay=delay
if symbol!=None:
self.symbol=symbol
if self.status:
self.stop(False)
self.start()
示例4: TimerWithResume
# 需要导入模块: from threading import Event [as 别名]
# 或者: from threading.Event import clear [as 别名]
class TimerWithResume(object):
def __init__(self, status_subject, refresh_interval):
self.status_subject = status_subject
self.abort = Event()
self.refresh_interval = refresh_interval
def perform(self):
while not self.abort.isSet():
self.status_subject.build_status()
self.abort.wait(self.refresh_interval)
def stop(self):
self.abort.set()
def start(self):
self.thread = Thread(target=self.perform)
self.thread.daemon = True
self.thread.start()
def resume(self):
self.thread.join()
self.abort.clear()
self.start()
def set_refresh_interval(self, new_interval):
self.refresh_interval = new_interval
示例5: PeriodicTimer
# 需要导入模块: from threading import Event [as 别名]
# 或者: from threading.Event import clear [as 别名]
class PeriodicTimer(object):
def __init__(self, frequency=60, *args, **kwargs):
self.is_stopped = Event()
self.is_stopped.clear()
self.interval = frequency
self._timer = Timer(self.frequency, self._check_for_event, ())
self._timer.daemon = True
@property
def interval(self):
return self.frequency
@interval.setter
def interval(self, frequency):
self.frequency = frequency
self.stop()
try:
if self._timer:
self._timer.cancel()
del(self._timer)
except AttributeError, ex:
pass
self._timer = Timer(self.frequency, self._check_for_event, ())
return self.frequency
示例6: HandleDataRequest
# 需要导入模块: from threading import Event [as 别名]
# 或者: from threading.Event import clear [as 别名]
class HandleDataRequest(QObject):
# Ensure data is obtained in the GUI thread
call = pyqtSignal(object, object)
def __init__(self):
QObject.__init__(self)
self.called = Event()
self.call.connect(self.run_func, Qt.QueuedConnection)
def run_func(self, func, data):
try:
self.result, self.tb = func(data), None
except Exception:
import traceback
self.result, self.tb = None, traceback.format_exc()
finally:
self.called.set()
def __call__(self, request):
func = data_funcs[request.type]
if is_gui_thread():
try:
return func(request.data), None
except Exception:
import traceback
return None, traceback.format_exc()
self.called.clear()
self.call.emit(func, request.data)
self.called.wait()
try:
return self.result, self.tb
finally:
del self.result, self.tb
示例7: wait_status
# 需要导入模块: from threading import Event [as 别名]
# 或者: from threading.Event import clear [as 别名]
def wait_status(self, status=win32service.SERVICE_RUNNING, timeout=SERVICE_WAIT_TIMEOUT):
abort = Event()
abort.clear()
def die():
abort.set()
timer = Timer(timeout, die)
timer.start()
current = None
while True:
if abort.is_set():
# If timeout is hit we abort.
log.warning("Timeout hit waiting service for status %s, current status %s",
status, current['CurrentState'])
return
current = win32service.QueryServiceStatusEx(self.service)
if current['CurrentState'] == status:
timer.cancel()
return
time.sleep(1)
示例8: Dispatcher
# 需要导入模块: from threading import Event [as 别名]
# 或者: from threading.Event import clear [as 别名]
class Dispatcher(Thread):
cueue = None
instance = None
cond = None
nextTrigger = None
def __init__(self):
Thread.__init__(self)
Dispatcher.instance = self
Dispatcher.cueue = []
self.cond = Condition(Lock())
self.evt = Event()
self.daemon = True
def run(self):
while True:
logger.debug("sleeping for %s" % self.nextTrigger)
self.evt.wait(self.nextTrigger)
n = now()
tasks = [ b for b in Dispatcher.cueue if b.triggerTime <= n ]
logger.debug("Doing %i callbacks" % len(tasks))
for t in tasks:
t.internal_callback()
if len(Dispatcher.cueue) > 0:
self.nextTrigger = min([b.triggerTime for b in Dispatcher.cueue]) - now()
else:
self.nextTrigger = None
self.evt.clear()
def __callLater(self, triggerTime, callback, *a, **kw):
t = Task(triggerTime, callback, *a, **kw)
Dispatcher.cueue.append(t)
if not self.nextTrigger or triggerTime < self.nextTrigger:
logger.debug("notifying condition")
# we need to trigger before the next event
self.evt.set()
self.nextTrigger = triggerTime
return t
@classmethod
def getPendings(klass):
return klass.cueue
@classmethod
def callLater(klass__, triggerTime, callback, *a, **kw):
return klass__.instance.__callLater(triggerTime, callback, *a, **kw)
@classmethod
def cancelCallLater(klass, task):
if task in klass.cueue:
task.cancel()
return True
return False
@classmethod
def cancelAll(klass):
for task in klass.cueue:
task.cancel()
klass.cueue = []
示例9: do_download
# 需要导入模块: from threading import Event [as 别名]
# 或者: from threading.Event import clear [as 别名]
def do_download():
# get activity registry
from jarabe.model.bundleregistry import get_registry
registry = get_registry() # requires a dbus-registered main loop
install_event = Event()
# progress bar bookkeeping.
counts = [0, self.activity_list.updates_selected(), 0]
def p(n, extra, icon):
if n is None:
progress_cb(n, extra, icon)
else:
progress_cb((n+(counts[0]/counts[1]))/2, extra, icon)
counts[2] = n # last fraction.
def q(n, row):
p(n, _('Downloading %s...') % row[model.DESCRIPTION_BIG],
row[model.ACTIVITY_ICON])
for row, f in self.activity_list.download_selected_updates(q):
if f is None: continue # cancelled or network error.
try:
p(counts[2], _('Examining %s...')%row[model.DESCRIPTION_BIG],
row[model.ACTIVITY_ICON])
b = actutils.BundleHelper(f)
p(counts[2], _('Installing %s...') % b.get_name(),
_svg2pixbuf(b.get_icon_data()))
install_event.clear()
GLib.idle_add(self.install_cb, registry, b, install_event)
install_event.wait()
except:
logging.exception("Failed to install bundle")
pass # XXX: use alert to indicate install failure.
if os.path.exists(f):
os.unlink(f)
counts[0]+=1
# refresh when we're done.
GObject.idle_add(self.refresh_cb, None, None, False)
示例10: myObj
# 需要导入模块: from threading import Event [as 别名]
# 或者: from threading.Event import clear [as 别名]
class myObj ():
def __init__(self, name, counter):
self._stopper = Event()
self.name = name
self.counter = counter
self.t = None
self.count = 0
def start(self):
self.t = Thread(name = self.name, target = self._doWork, args=(self.name, ) )
self.t.start()
def _doWork(self,threadName):
self._stopper.clear()
while not self._stopper.is_set():
print "%s: %s" % ( current_thread().getName(),time.ctime(time.time()) )
self.count += 1
self._stopper.wait(10)
print "Done"
print ("Count: %d"%self.count)
def stopit(self):
self._stopper.set()
self.t.join()
def stopped(self):
return self._stopper.is_set()
示例11: ExThread
# 需要导入模块: from threading import Event [as 别名]
# 或者: from threading.Event import clear [as 别名]
class ExThread(Thread):
def __init__(self, *args, **kw):
Thread.__init__(self, *args, **kw)
self._willKill = False
self._event = Event()
self._event.set()
def localtrace(self, why):
if self._willKill and why == "line":
raise SystemError()
elif not self._event.isSet():
self._event.wait()
return self.localtrace
def kill(self):
self._willKill = True
self.localtrace(why="line")
def pause(self):
self._event.clear()
def ahead(self):
self._event.set()
def run(self):
while True:
click_at_pos(500, 320)
time.sleep(0.1)
示例12: Sound
# 需要导入模块: from threading import Event [as 别名]
# 或者: from threading.Event import clear [as 别名]
class Sound(hass.Hass):
def initialize(self):
# Create Queue
self.queue = Queue(maxsize=0)
# Create worker thread
t = Thread(target=self.worker)
t.daemon = True
t.start()
self.event = Event()
def worker(self):
active = True
while active:
try:
# Get data from queue
data = self.queue.get()
if data["type"] == "terminate":
active = False
else:
# Save current volume
volume = self.get_state(self.args["player"], attribute="volume_level")
# Set to the desired volume
self.call_service("media_player/volume_set", entity_id = self.args["player"], volume_level = data["volume"])
if data["type"] == "tts":
# Call TTS service
self.call_service("tts/amazon_polly_say", entity_id = self.args["player"], message = data["text"])
if data["type"] == "play":
netpath = netpath = 'http://{}:{}/local/{}/{}'.format(self.args["ip"], self.args["port"], self.args["base"], data["path"])
self.call_service("media_player/play_media", entity_id = self.args["player"], media_content_id = netpath, media_content_type = data["content"])
# Sleep to allow message to complete before restoring volume
time.sleep(int(data["length"]))
# Restore volume
self.call_service("media_player/volume_set", entity_id = self.args["player"], volume_level = volume)
# Set state locally as well to avoid race condition
self.set_state(self.args["player"], attributes = {"volume_level": volume})
except:
self.log("Error")
self.log(sys.exc_info())
# Rinse and repeat
self.queue.task_done()
self.log("Worker thread exiting")
self.event.set()
def tts(self, text, volume, length):
self.queue.put({"type": "tts", "text": text, "volume": volume, "length": length})
def play(self, path, content, volume, length):
self.queue.put({"type": "play", "path": path, "content": content, "volume": volume, "length": length})
def terminate(self):
self.event.clear()
self.queue.put({"type": "terminate"})
self.event.wait()
示例13: event
# 需要导入模块: from threading import Event [as 别名]
# 或者: from threading.Event import clear [as 别名]
class event(object):
""" Class encapsulating an event object to control
sequential access to a resource """
def __init__(self, *args):
self.evt = Event()
self.evt.set()
def __call__(self, f):
def eventfunc(*args, **kwargs):
try:
print 'Waiting on event =>',currentThread()
self.evt.wait()
# First thread will clear the event and
# make others wait, once it is done with the
# job, it sets the event which wakes up
# another thread, which does the same thing...
# This provides sequential access to a
# resource...
self.evt.clear()
print 'Cleared event =>',currentThread()
try:
return f(*args, **kwargs)
except Exception, e:
raise
finally:
# Wake up another thread...
self.evt.set()
print 'Set event=>',currentThread()
return eventfunc
示例14: EventLoop
# 需要导入模块: from threading import Event [as 别名]
# 或者: from threading.Event import clear [as 别名]
class EventLoop(object):
def __init__(self):
self.registry = {}
self.threads = {}
self.queue = Queue.Queue()
self.run_flag = Event()
self.run_flag.set()
def register(self, name, thread_obj=None, event=None):
"""
If called with two parameters, they should be event to listen to and
the EventConsumer class that will listen to it.
If called with one parameter, it should be an EventEmitter class.
"""
if thread_obj is not None:
self.threads[name] = thread_obj
if event is not None:
if event not in self.registry:
self.registry[event] = []
if self.threads[name].add_event not in self.registry[event]:
self.registry[event].append(self.threads[name].add_event)
def unregister(self, event, name):
ev_thr = self.threads[name].add_event
print('unregister', event, name, ev_thr, self.registry[event])
if ev_thr in self.registry[event]:
self.registry[event].remove(ev_thr)
print(self.registry[event])
def add_event(self, event, value):
self.queue.put((event, value))
def run(self):
for name in self.threads:
self.threads[name].start()
while True:
try:
event, value = self.queue.get(True, 20)
if event == 'unregister':
self.unregister(*value)
if event not in self.registry:
print("Invalid event encountered %s with values %r!" %
(event, value))
for listener in self.registry[event]:
# print('call', listener, event, value)
listener(event, value)
except KeyboardInterrupt:
self.run_flag.clear()
for thread in self.threads:
print(thread)
self.threads[thread].join()
return
except Queue.Empty:
pass
示例15: Autoscroll
# 需要导入模块: from threading import Event [as 别名]
# 或者: from threading.Event import clear [as 别名]
class Autoscroll(Thread):
"""A Thread subclass that implements autoscroll timer."""
def __init__(self, widget):
"""Initialize the class."""
super().__init__()
self.daemon = True
self.widget = widget
self.event = Event()
def _can_scroll(self):
"""Return True if we can autoscroll."""
return (lyvi.player.length and lyvi.player.state == 'play' and lyvi.ui.view == 'lyrics'
and not lyvi.ui.hidden and self.widget.pos not in ('All', 'Bot'))
def run(self):
"""Start the timer."""
while True:
if self._can_scroll():
time = ceil(lyvi.player.length / (self.widget.total_lines - self.widget.size[1]))
reset = False
for _ in range(time):
if self.event.wait(1):
reset = True
self.event.clear()
break
if not reset and self._can_scroll():
self.widget.keypress(self.widget.size, 'down')
else:
sleep(1)
def reset(self):
"""Reset the timer."""
self.event.set()