• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python threading.Timer类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: initial

def initial():

		#UDP socket works
	print 'Waiting For Peers.... :)'
	sock_udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
	sock_udp.bind((SERVER_IP,SERVER_PORT))
	peer_data = ''
	t = Timer (TIMER_IDLE_PEER, timer_function)
	t.start()
	exp_seq=1
	old_buffer=''
		#Request from Peer
	while True:
		recv_buffer,addr = sock_udp.recvfrom(4096)
		if recv_buffer == 'list':
			sock_udp.sendto(str(peer_list), addr)
		else:
			sock_udp.sendto(recv_buffer,addr)
			if old_buffer != recv_buffer:
				old_buffer = recv_buffer
				recv_buffer_split = recv_buffer.split()
				recv_buffer_len = len(recv_buffer_split)
				num_pkts = recv_buffer_split.pop(recv_buffer_len-1)
				seq_pkt = recv_buffer_split.pop(recv_buffer_len-2)
				exp_seq=exp_seq+1
				peer_data = peer_data + ''.join((str(x)+' ') for x in recv_buffer_split)
				if num_pkts == seq_pkt:
					thread = Thread(target = process_packet, args = (peer_data,sock_udp,addr))
					thread.start() #TEST THREADING!!!!!!!!!!!!!!!!!!!!
					#thread.join()
					peer_data = ''
					exp_seq=1
开发者ID:navneet0408,项目名称:P2P-File-Transfer,代码行数:32,代码来源:Server.py


示例17: request_handler

 def request_handler(self):
    timeout = self.opcd.get('power_save_timeout')
    req = PowerReq()
    rep = PowerRep()
    timer = None
    while True:
       rep.status = OK
       try:
          req_data = self.ctrl_socket.recv()
       except:
          sleep(1)
          continue
       try:
          req.ParseFromString(req_data)
       except:
          rep.status = E_SYNTAX
       else:
          try:
             timer.cancel()
          except:
             pass
          if req.cmd == STAND_POWER:
             timer = Timer(timeout, self.power_off)
             timer.start()
          else:
             if self.critical:
                # flying command is not allowed if battery was critical:
                rep.status = E_POWER
             else:
                self.gpio_mosfet.set_gpio(self.power_pin, True)
       self.ctrl_socket.send(rep.SerializeToString())
开发者ID:erazor83,项目名称:PenguPilot,代码行数:31,代码来源:powerman.py


示例18: run

 def run(self):
     while self.is_running:
         try:
             super(SerializeThread, self).run()
         except Exception, e:
             log.error("Exception in thread %s: %s", self.name, e)
             delay = TIMER_DELAYS[self.name]
             if delay > MAX_DELAY:
                 num_attempts = int(math.log((delay/10), 2));
                 log.error("Giving up re-spawning serialization " 
                     "worker after %d seconds (%d attempts).", 
                     delay, num_attempts
                 )
                 notify_serialization_failure(None,
                     subject="Notice - Bungeni Serialization Workers",
                     body="""Unable to restart serialization worker.
                 Please check the Bungeni logs."""
                 )
             else:
                 log.info("Attempting to respawn serialization "
                     "consumer in %d seconds", delay
                 )
                 next_delay = delay * 2
                 timer = Timer(delay, init_thread, [], 
                     {"delay": next_delay })
                 timer.daemon = True
                 timer.start()
             self.is_running = False
             del TIMER_DELAYS[self.name]
开发者ID:BenoitTalbot,项目名称:bungeni-portal,代码行数:29,代码来源:serialize.py


示例19: InternalServer

class InternalServer(HTTPServer):

    def kill_me(self):
        self.shutdown()
        logging.info("The server's life has come to an end, pid: {}".format(os.getpid()))


    def reset_selfdestruct_timer(self):
        if self.self_destruct_timer:
            self.self_destruct_timer.cancel()

        self.self_destruct_timer = Timer(LIFESPAN, self.kill_me)
        self.self_destruct_timer.start()


    def __init__(self, server_address, RequestHandlerClass, 
                 bind_and_activate=True):

        HTTPServer.__init__(self, server_address, RequestHandlerClass, 
                            bind_and_activate=bind_and_activate)
        
        self.self_destruct_timer = None
        self.clients = 1
        self.reset_selfdestruct_timer()


    def suicide(self):
        self.clients -= 1
        if self.clients == 0:
            if self.self_destruct_timer is not None:
                self.self_destruct_timer.cancel()

            quick_and_painless_timer = Timer(0.1, self.kill_me)
            quick_and_painless_timer.start()
开发者ID:Mapotempo,项目名称:omim,代码行数:34,代码来源:testserver.py


示例20: clean_avisos

def clean_avisos():
    global avisos_n
    logger.info("avisos_n = 0")
    avisos_n = 0
    global hilo
    hilo = Timer(config['clean_time'], clean_avisos)
    hilo.start()
开发者ID:adrianlzt,项目名称:silenciator,代码行数:7,代码来源:silenciator.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python local.__init__函数代码示例发布时间:2022-05-27
下一篇:
Python threading.Thread类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap