当前位置: 首页>>代码示例>>Python>>正文


Python Event.wait方法代码示例

本文整理汇总了Python中threading.Event.wait方法的典型用法代码示例。如果您正苦于以下问题:Python Event.wait方法的具体用法?Python Event.wait怎么用?Python Event.wait使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在threading.Event的用法示例。


在下文中一共展示了Event.wait方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: TimerWithResume

# 需要导入模块: from threading import Event [as 别名]
# 或者: from threading.Event import wait [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
开发者ID:brancz,项目名称:xf-indicator,代码行数:28,代码来源:timer_with_resume.py

示例2: __init__

# 需要导入模块: from threading import Event [as 别名]
# 或者: from threading.Event import wait [as 别名]
class Actor:
    def __init__(self):
        self._mailbox = Queue()

    def send(self, msg):
        self._mailbox.put(msg)

    def recv(self):
        msg = self._mailbox.get()
        if msg is ActorExit:
            raise ActorExit()
        return msg

    def start(self):
        self._terminated = Event()
        t = Thread(target=self._bootstrap)
        t.daemon = True
        t.start()

    def _bootstrap(self):
        try:
            self.run()
        except ActorExit:
            pass
        finally:
            self._terminated.set()

    def join(self):
        self._terminated.wait()

    def run(self):
        while True:
            msg = self.recv()
开发者ID:bodii,项目名称:test-code,代码行数:35,代码来源:10.py

示例3: ResponseWaiter

# 需要导入模块: from threading import Event [as 别名]
# 或者: from threading.Event import wait [as 别名]
class ResponseWaiter(object):

    def __init__(self, connection, num_responses):
        self.connection = connection
        self.pending = num_responses
        self.error = None
        self.responses = [None] * num_responses
        self.event = Event()

    def got_response(self, response, index):
        with self.connection.lock:
            self.connection.in_flight -= 1
        if isinstance(response, Exception):
            self.error = response
            self.event.set()
        else:
            self.responses[index] = response
            self.pending -= 1
            if not self.pending:
                self.event.set()

    def deliver(self, timeout=None):
        self.event.wait(timeout)
        if self.error:
            raise self.error
        elif not self.event.is_set():
            raise OperationTimedOut()
        else:
            return self.responses
开发者ID:dizpers,项目名称:python-driver,代码行数:31,代码来源:connection.py

示例4: DeferredResponse

# 需要导入模块: from threading import Event [as 别名]
# 或者: from threading.Event import wait [as 别名]
class DeferredResponse( object ):
  """
  A deferred that resolves to a response from TSServer.
  """

  def __init__( self, timeout = RESPONSE_TIMEOUT_SECONDS ):
    self._event = Event()
    self._message = None
    self._timeout = timeout


  def resolve( self, message ):
    self._message = message
    self._event.set()


  def result( self ):
    self._event.wait( timeout = self._timeout )
    if not self._event.isSet():
      raise RuntimeError( 'Response Timeout' )
    message = self._message
    if not message[ 'success' ]:
      raise RuntimeError( message[ 'message' ] )
    if 'body' in message:
      return self._message[ 'body' ]
开发者ID:LukasScheucher,项目名称:ycmd,代码行数:27,代码来源:typescript_completer.py

示例5: waitForBackend

# 需要导入模块: from threading import Event [as 别名]
# 或者: from threading.Event import wait [as 别名]
    def waitForBackend(self, devid):

        frontpath = self.frontendPath(devid)
        # lookup a phantom 
        phantomPath = xstransact.Read(frontpath, 'phantom_vbd')
        if phantomPath is not None:
            log.debug("Waiting for %s's phantom %s.", devid, phantomPath)
            statusPath = phantomPath + '/' + HOTPLUG_STATUS_NODE
            ev = Event()
            result = { 'status': Timeout }
            xswatch(statusPath, hotplugStatusCallback, ev, result)
            ev.wait(DEVICE_CREATE_TIMEOUT)
            err = xstransact.Read(statusPath, HOTPLUG_ERROR_NODE)
            if result['status'] != 'Connected':
                return (result['status'], err)
            
        backpath = xstransact.Read(frontpath, "backend")


        if backpath:
            statusPath = backpath + '/' + HOTPLUG_STATUS_NODE
            ev = Event()
            result = { 'status': Timeout }

            xswatch(statusPath, hotplugStatusCallback, ev, result)

            ev.wait(DEVICE_CREATE_TIMEOUT)

            err = xstransact.Read(backpath, HOTPLUG_ERROR_NODE)

            return (result['status'], err)
        else:
            return (Missing, None)
开发者ID:mikesun,项目名称:xen-cow-checkpointing,代码行数:35,代码来源:DevController.py

示例6: TestInterruptibleDecorator

# 需要导入模块: from threading import Event [as 别名]
# 或者: from threading.Event import wait [as 别名]
class TestInterruptibleDecorator(TestCase):

    def setUp(self):
        self.quit_condition = False
        self.thread_started = Event()

    @interruptible
    def never_ending(self, cancellation_point):
        self.thread_started.set()
        while True:
            time.sleep(0.01)
            cancellation_point()

    def test_interruptible_decorator(self):
        """ Tests for the @interruptible decorator. """
        thread = Thread(target=self.never_ending, args=(
            lambda: _cancellation_point(lambda: self.quit_condition),))
        thread.start()

        # Wait until thread comes to live
        self.thread_started.wait()

        # Ask to it to quit within 20ms
        self.quit_condition = True
        time.sleep(0.02)

        # Thread is finished
        self.assertFalse(thread.is_alive())
开发者ID:abseabse,项目名称:gtg,代码行数:30,代码来源:test_interruptible.py

示例7: __init__

# 需要导入模块: from threading import Event [as 别名]
# 或者: from threading.Event import wait [as 别名]
class ResponseEvent:
    """Event which is fired when the response is returned for a request.

        For each request sent this event is created.
        An application can wait for the event to create a blocking request.
    """
    def __init__(self):
        self.__evt = Event()

    def waiting(self):
        return not self.__evt.isSet()

    def waitForResponse(self, timeOut=None):
        """blocks until the response arrived or timeout is reached."""
        self.__evt.wait(timeOut)
        if self.waiting():
            raise Timeout()
        else:
            if self.response["error"]:
                raise Exception(self.response["error"])
            else:
                return self.response["result"]

    def handleResponse(self, resp):
        self.response = resp
        self.__evt.set()
开发者ID:Afey,项目名称:pyjs,代码行数:28,代码来源:__init__.py

示例8: join

# 需要导入模块: from threading import Event [as 别名]
# 或者: from threading.Event import wait [as 别名]
	def join(self,server,channel,nick=None,port=6667):
		channel = channel.lower()
		self.connect(server,port,nick)
		status = self.get_status(server)
		connected_servers = set(status['servers'])
		if not server in connected_servers:
			print("Not connected...")
		if channel in set(status['servers'][server]['channels']):
			print("Joined already.")
			return
		else:
			print("Joining",channel)
			e = Event()
			def channel_joined(addr,event):
				if event['kind']=='irc':
					if event['command']=='JOIN':
						if event['trailing'].lower()==channel:
							status['servers'][server]['channels'].append(channel)
							self.events.unlisten(server,channel_joined)
							e.set()
			self.events.listen(server,channel_joined)
			self.events.broadcast({
				'event':'irc.command:'+server,
				'command':"JOIN",
				"arguments":[channel]
			})
			e.wait()
开发者ID:tyler-elric,项目名称:ircp2p,代码行数:29,代码来源:chat.py

示例9: InterruptableEvent

# 需要导入模块: from threading import Event [as 别名]
# 或者: from threading.Event import wait [as 别名]
class InterruptableEvent(object):
    """Event class for for Python v2.7 which behaves more like Python v3.2
    threading.Event and allows signals to interrupt waits"""

    def __init__(self):
        self.__event = Event()

    def is_set(self):
        return self.__event.is_set()

    def set(self):
        self.__event.set()

    def clear(self):
        self.__event.clear()

    def wait(self, timeout=None):
        # infinite
        if timeout is None:
            # event with timeout is interruptable
            while not self.__event.wait(60):
                pass
            return True

        # finite
        else:
            # underlying Event will perform timeout argument validation
            return self.__event.wait(timeout)
开发者ID:Iotic-Labs,项目名称:py-IoticAgent,代码行数:30,代码来源:thread_utils.py

示例10: WaitableTimer

# 需要导入模块: from threading import Event [as 别名]
# 或者: from threading.Event import wait [as 别名]
class WaitableTimer(Timer):
    def __init__(self, timeout, callback):
        Timer.__init__(self, timeout, callback)
        self.callback = callback
        self.event = Event()

        self.final_exception = None

    def finish(self, time_now):
        try:
            finished = Timer.finish(self, time_now)
            if finished:
                self.event.set()
                return True
            return False

        except Exception as e:
            self.final_exception = e
            self.event.set()
            return True

    def wait(self, timeout=None):
        self.event.wait(timeout)
        if self.final_exception:
            raise self.final_exception
开发者ID:datastax,项目名称:python-driver,代码行数:27,代码来源:asyncorereactor.py

示例11: RepeatTimer

# 需要导入模块: from threading import Event [as 别名]
# 或者: from threading.Event import wait [as 别名]
class RepeatTimer(Thread):

    def __init__(self, interval, function, stop_on_exception=True, args=[], kwargs={}):
        Thread.__init__(self)
        self.interval = interval
        self.function = function
        self.args = args
        self.kwargs = kwargs
        self.stop_on_exception = stop_on_exception
        self.finished = Event()

    def stop(self):
        self.done = True
        self.finished.set()

    def run(self):
        self.done = False
        while True:
            self.finished.wait(self.interval)
            if self.done:
                self.finished.clear()
                break
            if not self.finished.is_set():
                try:
                    self.function(*self.args, **self.kwargs)
                except Exception, e:
                    if self.stop_on_exception:
                        self.finished.clear()
                        raise
                    # XXX Not strictly for auth'ing, think of something better
                    log.exception('Login Fail')
            self.finished.clear()
开发者ID:ustbgaofan,项目名称:beaker,代码行数:34,代码来源:helpers.py

示例12: Worker

# 需要导入模块: from threading import Event [as 别名]
# 或者: from threading.Event import wait [as 别名]
  class Worker(Thread):
	  
    def __init__(self):
      Thread.__init__(self)
      self.trigger = Event()
      self.uri = None
      self.sonos = None
      self.daemon = True
      self.lock = Lock()

    def start_url(self, a_group, uri):
      with self.lock:
		self.sonos = a_group
		self.uri = uri
      self.trigger.set()

    
    def run(self):
      while True:
        self.trigger.wait()
        if self.sonos is None:
		  # take this as a sign to shut down gracefully
          break
        with self.lock:
          uri = self.uri
          self.uri = None
          self.trigger.clear()
        result = self.sonos.play_uri( uri)
        print result
开发者ID:phut,项目名称:SoCo,代码行数:31,代码来源:sonoseventhandler.py

示例13: CheckForUpdates

# 需要导入模块: from threading import Event [as 别名]
# 或者: from threading.Event import wait [as 别名]
class CheckForUpdates(Thread):

    INTERVAL = 24*60*60  # seconds
    daemon = True

    def __init__(self, parent):
        Thread.__init__(self)
        self.shutdown_event = Event()
        self.signal = Signal(parent)

    def run(self):
        while not self.shutdown_event.is_set():
            calibre_update_version = NO_CALIBRE_UPDATE
            plugins_update_found = 0
            try:
                version = get_newest_version()
                if version[:2] > numeric_version[:2]:
                    calibre_update_version = version
            except Exception as e:
                prints('Failed to check for calibre update:', as_unicode(e))
            try:
                update_plugins = get_plugin_updates_available(raise_error=True)
                if update_plugins is not None:
                    plugins_update_found = len(update_plugins)
            except Exception as e:
                prints('Failed to check for plugin update:', as_unicode(e))
            if calibre_update_version != NO_CALIBRE_UPDATE or plugins_update_found > 0:
                self.signal.update_found.emit(calibre_update_version, plugins_update_found)
            self.shutdown_event.wait(self.INTERVAL)

    def shutdown(self):
        self.shutdown_event.set()
开发者ID:artbycrunk,项目名称:calibre,代码行数:34,代码来源:update.py

示例14: TestInterruptible

# 需要导入模块: from threading import Event [as 别名]
# 或者: from threading.Event import wait [as 别名]
class TestInterruptible(unittest.TestCase):
    """ Tests for interrupting cooperative threads """

    def test_interruptible_decorator(self):
        """ Tests for the @interruptible decorator. """
        self.quit_condition = False
        cancellation_point = lambda: _cancellation_point(
            lambda: self.quit_condition)
        self.thread_started = Event()

        @interruptible
        def never_ending(cancellation_point):
            self.thread_started.set()
            while True:
                time.sleep(0.1)
                cancellation_point()
        thread = Thread(target=never_ending, args=(cancellation_point, ))
        thread.start()
        self.thread_started.wait()
        self.quit_condition = True
        countdown = 10
        while thread.is_alive() and countdown > 0:
            time.sleep(0.1)
            countdown -= 1
        self.assertFalse(thread.is_alive())
开发者ID:MonamAgarwal,项目名称:final,代码行数:27,代码来源:test_interruptible.py

示例15: TriggerEventWait

# 需要导入模块: from threading import Event [as 别名]
# 或者: from threading.Event import wait [as 别名]
    def TriggerEventWait(
        self,
        suffix,
        payload=None,
        prefix="Main",
        source=eg
    ):
        event = EventGhostEvent(suffix, payload, prefix, source)
        if event.source in self.filters:
            for filterFunc in self.filters[event.source]:
                if filterFunc(event) is True:
                    return event
        executed = Event()

        def Execute():
            try:
                event.Execute()
            finally:
                executed.set()

        def Transfer():
            ActionThreadCall(Execute)
            event.SetShouldEnd()

        self.AppendAction(Transfer)
        executed.wait(5.0)
        if not executed.isSet():
            eg.PrintWarningNotice(
                "timeout TriggerEventWait\n", traceback.format_stack()
            )
        return event
开发者ID:topic2k,项目名称:EventGhost,代码行数:33,代码来源:EventThread.py


注:本文中的threading.Event.wait方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。