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


Python threading.Timer类代码示例

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


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

示例1: test_sqs_longpoll

    def test_sqs_longpoll(self):
        c = SQSConnection()
        queue_name = "test_sqs_longpoll_%s" % int(time.time())
        queue = c.create_queue(queue_name)
        self.addCleanup(c.delete_queue, queue, True)
        messages = []

        # The basic idea is to spawn a timer thread that will put something
        # on the queue in 5 seconds and verify that our long polling client
        # sees the message after waiting for approximately that long.
        def send_message():
            messages.append(queue.write(queue.new_message("this is a test message")))

        t = Timer(5.0, send_message)
        t.start()
        self.addCleanup(t.join)

        start = time.time()
        response = queue.read(wait_time_seconds=10)
        end = time.time()

        t.join()
        self.assertEqual(response.id, messages[0].id)
        self.assertEqual(response.get_body(), messages[0].get_body())
        # The timer thread should send the message in 5 seconds, so
        # we're giving +- .5 seconds for the total time the queue
        # was blocked on the read call.
        self.assertTrue(4.5 <= (end - start) <= 5.5)
开发者ID:9seconds,项目名称:boto,代码行数:28,代码来源:test_connection.py

示例2: run

def run(data, d=None):
	global timer
	print(data)

	if data == "ring":
		if int(d) == 1:
			if timer:
				timer.cancel()

			timer = Timer(60, genugdavon)
			timer.start()

			check = Thread(target=check_locks)
			check.start()

			putfile('/sys/class/gpio/gpio11/value', '0')

			playsound("/root/ring-bb.wav")
		else:
			playsound("/root/ring-fis.wav")
	

	if data == "open":
#		if not locked_oben:
		playsound("/root/open.wav")
	
	if data == "summ":
		if timer:
			timer.cancel()

#		if not locked_oben:
		putfile('/sys/class/gpio/gpio11/value', '1')
		playsound("/root/summ.wav")
开发者ID:Chaotikum,项目名称:klingel,代码行数:33,代码来源:klingel.py

示例3: Countdown

class Countdown(object):
    """
    Countdown timer starts immediatly on init from `start_value` and counts down
    to zero, then counts up with negated time. Only displays minutes and
    seconds. No pause or reset available. Each "tick" of the clock is passed to
    the callback function as a string. """
    
    def __init__(self, start_value, callback):
        self._finished = False
        self.start_value = start_value
        self.callback = callback
        self.start_time = now()
        self._update()

    def _update(self):
        self._set_time(now() - self.start_time)
        if not self._finished:
            self._timer = Timer(1, self._update)
            self._timer.start()

    def _set_time(self, value):
        neg = '' 
        if self.start_value > value:
            value = self.start_value - value
        elif self.start_value < value:
            value = value - self.start_value
            neg = '-'
        else:
            value = 0
        mm, ss = divmod(value, 60)
        self.callback("{}{:02d}:{:02d}".format(neg, mm, ss))

    def stop(self):
        self._timer.cancel()
        self._finished = True
开发者ID:waylan,项目名称:mt,代码行数:35,代码来源:server.py

示例4: InfiniteTimer

class InfiniteTimer():
    """A Timer class that does not stop, unless you want it to."""

    def __init__(self, seconds, target):
        self._should_continue = False
        self.is_running = False
        self.seconds = seconds
        self.target = target
        self.thread = None

    def _handle_target(self):
        self.is_running = True
        self.target()
        self.is_running = False
        self._start_timer()

    def _start_timer(self):
        if self._should_continue:  # Code could have been running when cancel was called.
            self.thread = Timer(self.seconds, self._handle_target)
            self.thread.start()

    def start(self):
        if not self._should_continue and not self.is_running:
            self._should_continue = True
            self._start_timer()
        else:
            print("Timer already started or running, please wait if you're restarting.")

    def cancel(self):
        if self.thread is not None:
            # Just in case thread is running and cancel fails.
            self._should_continue = False
            self.thread.cancel()
        else:
            print("Timer never started or failed to initialize.")
开发者ID:MediaKraken,项目名称:MediaKraken_Deployment,代码行数:35,代码来源:common_timer.py

示例5: run

def run(dir, main="tmp"):
    try:
        ##print("DEBUG:", [
        ## config.JAVA_CMD,
        ##    "-Djava.security.manager",
        ##    "-Djava.security.policy=whiley.policy",
        ##    "-cp",config.WYJC_JAR + ":" + dir,
        ##    main
        ##    ])
        # run the JVM
        proc = subprocess.Popen([
                                    config.JAVA_CMD,
                                    "-Djava.security.manager",
                                    "-Djava.security.policy=whiley.policy",
                                    "-cp", config.WYJC_JAR + ":" + dir,
                                    main
                                ], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=False)
        # Configure Timeout
        kill_proc = lambda p: p.kill()
        timer = Timer(20, kill_proc, [proc])
        timer.start()
        # Run process        
        (out, err) = proc.communicate()
        timer.cancel()
        # Check what happened
        if proc.returncode >= 0:
            return out
        else:
            return "Timeout: Your program ran for too long!"
    except Exception as ex:
        # error, so return that
        return "Run Error: " + str(ex)
开发者ID:alcinnz,项目名称:WyWeb,代码行数:32,代码来源:main.py

示例6: Handler

class Handler():
    """Queues filesystem events for broadcast"""

    def __init__(self):
        """Create an event handler"""
        ## Timer used to prevent notification floods
        self._timer = None
        ## The files that have changed since the last broadcast
        self._files = set()
        ## Lock to protect files and timer from threading issues
        self._lock = Lock()

    def broadcast(self):
        """Broadcasts a list of all files touched since last broadcast"""
        with self._lock:
            cola.notifier().broadcast(signals.update_status, self._files)
            self._files = set()
            self._timer = None

    def handle(self, path):
        """Queues up filesystem events for broadcast"""
        with self._lock:
            self._files.add(path)
            if self._timer is None:
                self._timer = Timer(0.333, self.broadcast)
                self._timer.start()
开发者ID:dcfrancisco,项目名称:git-cola,代码行数:26,代码来源:inotify.py

示例7: setupClient

    def setupClient(self, topic, msg_type, wait_duration=10):
        """
        Tries to set up an action client for calling it later.
        
        @type topic: string
        @param topic: The topic of the action to call.
        
        @type msg_type: msg type
        @param msg_type: The type of messages of this action client.
        
        @type wait_duration: int
        @param wait_duration: Defines how long to wait for the given client if it is not available right now.
        """
        if topic not in ProxyActionClient._clients:
            client = actionlib.SimpleActionClient(topic, msg_type)
            t = Timer(1, self._print_wait_warning, [topic])
            t.start()
            available = client.wait_for_server(rospy.Duration.from_sec(wait_duration))
            warning_sent = False
            try:
                t.cancel()
            except Exception as ve:
                # already printed the warning
                warning_sent = True

            if not available:
                Logger.logerr("Action client %s timed out!" % topic)
            else:
                ProxyActionClient._clients[topic] = client
                if warning_sent:
                    Logger.loginfo("Finally found action client %s..." % (topic))
开发者ID:birlrobotics,项目名称:flexbe_behavior_engine,代码行数:31,代码来源:proxy_action_client.py

示例8: view_image

 def view_image(self, im, auto_close=True):
     # use a manager to open so will auto close on quit
     self.open_view(im)
     if auto_close:
         minutes = 2
         t = Timer(60 * minutes, im.close_ui)
         t.start()
开发者ID:UManPychron,项目名称:pychron,代码行数:7,代码来源:machine_vision_manager.py

示例9: run

  def run(self, app, type):
    # Invoke wren and run the test.
    test_arg = self.path
    if type == "api test":
      # Just pass the suite name to API tests.
      test_arg = basename(splitext(test_arg)[0])

    proc = Popen([app, test_arg], stdin=PIPE, stdout=PIPE, stderr=PIPE)

    # If a test takes longer than two seconds, kill it.
    #
    # This is mainly useful for running the tests while stress testing the GC,
    # which can make a few pathological tests much slower.
    timed_out = [False]
    def kill_process(p):
      timed_out[0] = True
      p.kill()

    timer = Timer(2, kill_process, [proc])

    try:
      timer.start()
      out, err = proc.communicate(self.input_bytes)

      if timed_out[0]:
        self.fail("Timed out.")
      else:
        self.validate(type == "example", proc.returncode, out, err)
    finally:
      timer.cancel()
开发者ID:Rohansi,项目名称:wren,代码行数:30,代码来源:test.py

示例10: PeriodicTimer

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
开发者ID:chrisleck-old-personal,项目名称:pytomation,代码行数:26,代码来源:periodic_timer.py

示例11: TimerMixIn

class TimerMixIn(object):
  
    def __init__(self, *argl, **argd):
        super(TimerMixIn,self).__init__(*argl,**argd)
        self.timer = None
        self.timerSuccess = True
          
    def startTimer(self, secs):
        if self.timer is not None:
            self.cancelTimer()
        self.timer = Timer(secs, self.__handleTimerDone)
        self.timerSuccess = False
        self.timer.start()
  
    def cancelTimer(self):
        if self.timer is not None and self.timer:
             self.timer.cancel()
             self.timer = None
             self.timerSuccess = False
  
    def timerRunning(self):
        return self.timer is not None
        
    def timerWasCancelled(self):
        return not self.timerSuccess
  
    def __handleTimerDone(self):
        self.scheduler.wakeThread(self)
        self.timer = None
        self.timerSuccess = True
开发者ID:casibbald,项目名称:kamaelia,代码行数:30,代码来源:TimerMixIn.py

示例12: dataout

def dataout():
    global timer1
    timer1 = Timer(1.0 / data_freq, dataout)
    timer1.start()
    lock.acquire()
    print "{:+.3f}".format(data.popleft())
    lock.release()
开发者ID:menuojo,项目名称:dev_python,代码行数:7,代码来源:producer.py

示例13: create_session

 def create_session(self):
     log.info("Enabling for MAC %s" % (self.mac))
     sys_cmd = "iptables -I internet 1 -t mangle -m mac --mac-source %s -j RETURN" % self.mac
     log.info(sys_cmd)
     log.info(os.popen(sys_cmd).read())
     callback = Timer(self.length, self.destroy_session)
     callback.start()
开发者ID:Mrkebubun,项目名称:BitcoinWifi,代码行数:7,代码来源:session.py

示例14: defer

 def defer(self, t, run_on_cancel, func, *args):
     event = Timer(t, self.run_action, kwargs={'func': func, 'args': args})
     event.name = '%s deferring %s' % (event.name, func.__name__)
     event.start()
     with worker_lock:
         self.events[event.ident] = Event(event, run_on_cancel)
     return event.ident
开发者ID:bobtwinkles,项目名称:cslbot,代码行数:7,代码来源:workers.py

示例15: _connected

    def _connected(self, link_uri):
        """ This callback is called form the Crazyflie API when a Crazyflie
        has been connected and the TOCs have been downloaded."""
        print('Connected to %s' % link_uri)

        # The definition of the logconfig can be made before connecting
        self._lg_stab = LogConfig(name='Stabilizer', period_in_ms=10)
        self._lg_stab.add_variable('stabilizer.roll', 'float')
        self._lg_stab.add_variable('stabilizer.pitch', 'float')
        self._lg_stab.add_variable('stabilizer.yaw', 'float')

        # Adding the configuration cannot be done until a Crazyflie is
        # connected, since we need to check that the variables we
        # would like to log are in the TOC.
        try:
            self._cf.log.add_config(self._lg_stab)
            # This callback will receive the data
            self._lg_stab.data_received_cb.add_callback(self._stab_log_data)
            # This callback will be called on errors
            self._lg_stab.error_cb.add_callback(self._stab_log_error)
            # Start the logging
            self._lg_stab.start()
        except KeyError as e:
            print('Could not start log configuration,'
                  '{} not found in TOC'.format(str(e)))
        except AttributeError:
            print('Could not add Stabilizer log config, bad configuration.')

        # Start a timer to disconnect in 10s
        t = Timer(5, self._cf.close_link)
        t.start()
开发者ID:Allenbit,项目名称:crazyflie-lib-python,代码行数:31,代码来源:basiclog.py


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