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

Python threading._sleep函数代码示例

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

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



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

示例1: age_timer

def age_timer(nme):
	"""
		age timer thread
	"""
	interval_time=2

	while nme.age_exit_flag is False:#thread not safe,but it does no matter
		threading._sleep(interval_time)
		nme.nme_lock.acquire()
		del_lst=set()
		#print "meeeow"
		#traverse the node table,fidn these expired node,and recollect them
		for nod in nme.node_tbl:
			if nme.node_tbl[nod].timer_cnt > nme.node_expiry_time:
				nme.node_tbl[nod].node_expiry_callback()
				del_lst.add(nod)
			else :
				nme.node_tbl[nod].timer_cnt+=interval_time
		for ele in del_lst:
			if ele in nme.node_tbl:
				#nme.node_id_pool.discard(ele)
				#nme.node_uuid_pool.discard(nme.node_tbl[ele].uuid)
				nme.node_delete(ele)
				#del nme.node_tbl[ele]
				#nme.node_delete(ele)
		#help(nme)
		nme.nme_lock.release()
开发者ID:chillancezen,项目名称:ddn,代码行数:27,代码来源:node_mng.py


示例2: display_current_message_in_thread

    def display_current_message_in_thread(self):
        time_called = time.time()
        self.message_set_time = time_called
        rows = (len(self.message.message_text) / 16) + 1
        lines = []
        for i in xrange(rows):
            start = i * 16
            end = start + 16
            lines.append(self.message.message_text[start:end])
        if len(lines) == 1:
            lines.append("")
        size = len(lines)
        pairs = zip(lines[0 : size-1], lines[1:size])
        strings = ['\n'.join(p) for p in pairs]
        strings.append(strings[0])

        self.set_lcd_on_time(3 * len(strings))

        for s in strings:
            if self.message_set_time > time_called:
                return
            self.lcd.clear()
            self.logger.debug('displaying:\n%s' % s)
            self.lcd.message(s)
            threading._sleep(3)
开发者ID:nmacinnis,项目名称:txlcd,代码行数:25,代码来源:buttonmasher.py


示例3: run

 def run(self):
     from random import random
     counter = 0
     while counter < self.quota:
         counter = counter + 1
         self.queue.put("%s.%d" % (self.getName(), counter))
         threading._sleep(random() * 0.00001)
开发者ID:funny-falcon,项目名称:pyvm,代码行数:7,代码来源:mod.threading.py


示例4: get_announcement

 def get_announcement(self):
     '''Connect to the announcing socket and get an analysis announcement
     
     returns an analysis_id / worker_request address pair
     
     raises a CancelledException if we detect cancellation.
     '''
     poller = zmq.Poller()
     poller.register(self.notify_socket, zmq.POLLIN)
     announce_socket = the_zmq_context.socket(zmq.SUB)
     announce_socket.setsockopt(zmq.SUBSCRIBE, "")
     announce_socket.connect(self.work_announce_address)
     try:
         poller.register(announce_socket, zmq.POLLIN)
         while True:
             for socket, state in poller.poll():
                 if socket == self.notify_socket and state == zmq.POLLIN:
                     msg = self.notify_socket.recv()
                     if msg == NOTIFY_STOP:
                         from cellprofiler.pipeline import CancelledException
                         self.cancelled = True
                         raise CancelledException()
                 elif socket == announce_socket and state == zmq.POLLIN:
                     announcement = dict(announce_socket.recv_json())
                     if len(announcement) == 0:
                         threading._sleep(0.25)
                         continue
                     if self.current_analysis_id in announcement:
                         analysis_id = self.current_analysis_id
                     else:
                         analysis_id = random.choice(announcement.keys())
                     return analysis_id, announcement[analysis_id]
     finally:
         announce_socket.close()
开发者ID:jiashunzheng,项目名称:CellProfiler,代码行数:34,代码来源:analysis_worker.py


示例5: Update

    def Update(self):
        assert self.host_socket != None

        self.iters += 1

        ## securely connect to server with existing or new account
        ##   c:LOGIN -> {s:LOGACCEPT,s:LOGDENIED}
        ##     if s:LOGACCEPT -> done
        ##     if s:LOGDENIED -> c:REGISTER
        ##     c:REGISTER -> {s:REGACCEPT,s:REGDENIED}
        ##       if s:REGACCEPT -> c:LOGIN -> s:AGREEMENT -> (c:CONFAGREE, c:LOGIN) -> s:LOGACCEPT
        ##       if s:REGDENIED -> exit
        if self.client_acked_shared_key or (not self.want_secure_session):
            if not self.requested_authentication:
                self.out_LOGIN()

                ## periodically re-negotiate the session key (every
                ## 500*0.05=25.0s; models an ultra-paranoid client)
        if self.client_acked_shared_key and self.want_secure_session and self.use_secure_session():
            if (self.iters % 50) == 0:
                self.reset_session_state()
                self.out_SETSHAREDKEY()

        if (self.iters % 10) == 0:
            self.out_PING()

        threading._sleep(0.05)

        ## eat through received data
        self.Recv()
开发者ID:marslabtron,项目名称:uberserver,代码行数:30,代码来源:TestLobbyClient.py


示例6: acquire

    def acquire(self,blocking=True,timeout=None):
        """Attempt to acquire this lock.

        If the optional argument "blocking" is True and "timeout" is None,
        this methods blocks until is successfully acquires the lock.  If
        "blocking" is False, it returns immediately if the lock could not
        be acquired.  Otherwise, it blocks for at most "timeout" seconds
        trying to acquire the lock.

        In all cases, this methods returns True if the lock was successfully
        acquired and False otherwise.
        """
        if timeout is None:
            return self.__lock.acquire(blocking)
        else:
            #  Simulated timeout using progressively longer sleeps.
            #  This is the same timeout scheme used in the stdlib Condition
            #  class.  If there's lots of contention on the lock then there's
            #  a good chance you won't get it; but then again, Python doesn't
            #  guarantee fairness anyway.  We hope that platform-specific
            #  extensions can provide a better mechanism.
            endtime = _time() + timeout
            delay = 0.0005
            while not self.__lock.acquire(False):
                remaining = endtime - _time()
                if remaining <= 0:
                    return False
                delay = min(delay*2,remaining,0.05)
                _sleep(delay)
            return True
开发者ID:rfk,项目名称:threading2,代码行数:30,代码来源:t2_base.py


示例7: shutDown

	def shutDown(self, restart=False):
		f = open(self.lang["shutdown"])
		shutText = f.read()
		f.close()

		self.text = ""
		self.updateText()

		height = self.height*3
		width = self.width*2
		cw = self.font.measure('A')
		ch = self.font.metrics("linespace")
		self.th = height/ch
		self.lw = width/cw
		self.config(foreground="white", height=self.th, width=self.lw)

		shutTime = self.shutTime #secs
		timepl = shutTime/len(shutText.split('\n'))

		for c in shutText.split('\n'):
			if len(c) > 1:
				if not c.endswith('.'):
					self.printOut(c + '\n')
				else:
					self.printOut(c)
			threading._sleep(timepl)

		if restart:
			self.state = const.states.restart
		else:
			self.state = const.states.shutdown
		self.event_generate("<<shut>>")
开发者ID:kadircet,项目名称:HackME,代码行数:32,代码来源:shutdown.py


示例8: run

 def run(self):
     """
         RUN is a magic name in the Threading Library
     """
     threading._sleep(self.sleeptime)
     self.funktion( *self.args)
     exit()
开发者ID:julzhk,项目名称:rasp-pi-video,代码行数:7,代码来源:threaded_timer.py


示例9: run

    def run(self, kismet_queue, sql_queue):

        d = dict()                                                      # Create dictionary (a.k.a Open hash-table (separate chaining))

        while not self.dh_quit:                                         # Loop while we want to process data

            timeout = time.time() + 60*2                                # 60*x min timeout
            d.clear()                                                   # Clear the dictionary for the next sql_queue put
            mac_array = []                                              # Clear the mac_array for the next sql_queue put

            while True:                                                 # nested while loop that runs for the timeout mins specified above.

                q_data = kismet_queue.get()                             # Get data from the queue. The data is 1 client. (mac, signal_dbm, conn_type, date, time, host_name)
                mac_key = q_data.split(' ')[1]                          # Split the mac address so we can use the mac address as a index address for the dictionary

                if mac_key not in d:                                    # if MAC Address is not in table. Add it
                    d[mac_key] = q_data                                 # Set the mac index address value equal to the queue data which contains the rest of the information on that client

                if(time.time() >= timeout):                             # if it has been X mins put the the mac_array on the SQL queue
                    for item in d:                                      # Lopp through each item in the dictionary. each item is 1 clients data.
                        split = d[item].split(' ')                      # Split the data for each client so we can append the data to the mac_array as a tuple.

                        if(split[3] == '2'):                            # if the conn_type = '2' then its a probe request. append to mac_array for the sql_queue.
                            mac_array.append((split[1], split[2], split[3], split[4], split[5], split[6]))      # append it.
                    break                                               # Break out of the nested while loop. This will allow the main while loop to put the data to the sql_queue
                else:
                    threading._sleep(0.02)                              # Slow down the execution of the thread so its not going crazy
                    ### Debigging - print q_data

            sql_queue.put(mac_array)                                    # Add the mac_array to the sql_queue


        print "DATA HANDLER: STOPPED"
        return
开发者ID:Youssifm,项目名称:Kismet-Client,代码行数:34,代码来源:Kismet+SQL+client+-+v1.3.py


示例10: Click

def Click():
    global clicks
    global click_speed
    global pos
    while(True):
        if clicks:
            clickSpot(pos)
            threading._sleep(click_speed)
开发者ID:alprkskn,项目名称:SimpleClickerBot,代码行数:8,代码来源:ClickerHero.py


示例11: set_range

 def set_range():
     start, end = 0, 1
     while end < 10e6:
         end *= 1.0001
         leg.unit = 'm'
         leg.range = (start, end)
         threading._sleep(0.0005)
     self.frame.Destroy()
开发者ID:pieleric,项目名称:odemis-old,代码行数:8,代码来源:comp_legend_test.py


示例12: check_buttons

 def check_buttons(self):
     while self.checking:
         pressed_buttons = filter(
             lambda b: self.lcd.buttonPressed(b),
             range(0, 5)
         )
         if pressed_buttons:
             return pressed_buttons[0]
         threading._sleep(.1)
开发者ID:nmacinnis,项目名称:txlcd,代码行数:9,代码来源:buttonmasher.py


示例13: set_system_state

def set_system_state(to_state, current_state):
    if to_state == state.UNKNOWN:
        LOG.error('Trying to set system status UNKNOWN.... Uncool... bailing.  Current state: %s',
                  state.print_state(current_state))
        return

    def _set_system_state(s):
        LOG.info('Setting system mode: %s', state.print_state(s))
        if s == state.HEAT:
            _heat_on()
        elif s == state.COOL:
            _cool_on()
        elif s == state.FAN_ONLY:
            _fan_only()
        elif s == state.OFF:
            _off()

        # Verify that the system state was set currently
        threading._sleep(1)
        cs, _ = get_system_state()
        if s != cs:
            LOG.error('The system state was not set correctly!  Expected state: %s, Actual state: %s',
                      state.print_state(s), state.print_state(cs))

    def _heat_on():
        LOG.debug('Setting system mode to HEAT')
        _set_outputs(green=True, white=True)

    def _cool_on():
        LOG.debug('Setting system mode to COOL')
        _set_outputs(green=True, white=True, yellow=True)

    def _fan_only():
        LOG.debug('Setting system mode to FAN ONLY')
        _set_outputs(green=True)

    def _off():
        LOG.debug('Setting system mode to OFF')
        _set_outputs()

    def _set_outputs(green=False, white=False, yellow=False):
        LOG.debug('Setting GREEN out pin to %s', 'ON' if green else 'OFF')
        GPIO.output(CONF.io.green_pin_out, green)

        LOG.debug('Setting WHITE out pin to %s', 'ON' if white else 'OFF')
        GPIO.output(CONF.io.white_pin_out, white)

        LOG.debug('Setting YELLOW out pin to %s', 'ON' if yellow else 'OFF')
        GPIO.output(CONF.io.yellow_pin_out, yellow)

    if current_state in [state.OFF, state.FAN_ONLY]:
        _set_system_state(to_state)
    else:
        # First set the system to fan only to let the system cool down for 2 minutes, then set the system state
        _set_system_state(state.FAN_ONLY)
        threading._sleep(CONF.hvac.on_mode_change_fan_interval)
        _set_system_state(to_state)
开发者ID:alanquillin,项目名称:myhvac_service,代码行数:57,代码来源:hvac.py


示例14: test_newest

 def test_newest(self):
     import threading
     Project.objects.create(name="test1")
     threading._sleep(0.001)
     Project.objects.create(name="test2")
     threading._sleep(0.001)
     Project.objects.create(name="test3")
     newest = Project.objects.newest()[0]
     self.assertEquals('test3', newest.name)
开发者ID:frombegin,项目名称:django-boilerplate,代码行数:9,代码来源:tests.py


示例15: generalTask

def generalTask():
    lastPageIndex = 0
    while True:
        if taskQueue.qsize()==0:
            print "current : "+str(lastPageIndex)
            for i in range(0,100):
                taskQueue.put(lastPageIndex)
                lastPageIndex+=1

        threading._sleep(1)
开发者ID:yrjyrj123,项目名称:ziRoom,代码行数:10,代码来源:ziRoom.py


示例16: test_lock_created_for_each_key

 def test_lock_created_for_each_key(self):
     locks = []
     thread1 = LockCreatorThread(self.generic_lock_provider, locks)
     thread2 = LockCreatorThread(self.generic_lock_provider, locks)
     thread1.start()
     thread2.start()
     while len(locks) < 12:
         threading._sleep(0.001)
     self.assertEquals(len(locks), 12)
     self.assertEquals(len(list(set(locks))), 6)
开发者ID:QualiSystems,项目名称:Azure-Shell,代码行数:10,代码来源:test_generic_lock_provider.py


示例17: OpenSocket

	def OpenSocket(self, server_addr):
		while (self.host_socket == None):
			try:
				## non-blocking so we do not have to wait on server
				self.host_socket = socket.create_connection(server_addr, 5)
				self.host_socket.setblocking(0)
			except socket.error as msg:
				print("[OpenSocket] %s" % msg)
				## print(traceback.format_exc())
				threading._sleep(0.5)
开发者ID:gajop,项目名称:uberserver-1,代码行数:10,代码来源:stresstest.py


示例18: light_lcd_screen

 def light_lcd_screen(self):
     while self.checking:
         self.lcd_backlight_semaphore.acquire()
         if self.lcd_time > 0:
             self.lcd_time -= 1
             self.lcd.backlight(self.lcd.TEAL)
         else:
             self.lcd.backlight(self.lcd.OFF)
         self.lcd_backlight_semaphore.release()
         threading._sleep(1)
开发者ID:nmacinnis,项目名称:txlcd,代码行数:10,代码来源:buttonmasher.py


示例19: wait

	def wait(self, timeout=None):
		waiter = _allocate_lock()
		waiter.acquire()				# get it the first time, no blocking
		self.append(waiter)
		
		
		try:
			# restore state no matter what (e.g., KeyboardInterrupt)
			# now we block, as we hold the lock already
			# in the momemnt we release our lock, someone else might actually resume
			self._lock.release()
			if timeout is None:
				waiter.acquire()
			else:
				# Balancing act:  We can't afford a pure busy loop, because of the 
				# GIL, so we have to sleep
				# We try to sleep only tiny amounts of time though to be very responsive
				# NOTE: this branch is not used by the async system anyway, but 
				# will be hit when the user reads with timeout 
				endtime = _time() + timeout
				delay = self.delay
				acquire = waiter.acquire
				while True:
					gotit = acquire(0)
					if gotit:
						break
					remaining = endtime - _time()
					if remaining <= 0:
						break
					# this makes 4 threads working as good as two, but of course
					# it causes more frequent micro-sleeping
					#delay = min(delay * 2, remaining, .05)
					_sleep(delay)
				# END endless loop
				if not gotit:
					try:
						self.remove(waiter)
					except AttributeError:
						# handle python 2.4 - actually this should be made thread-safe
						# but lets see ... 
						try:
							# lets hope we pop the right one - we don't loop over it
							# yet-we just keep minimal compatability with py 2.4
							item = self.pop()
							if item != waiter:
								self.append(item)
						except IndexError:
							pass
					except ValueError:
						pass
				# END didn't ever get it
		finally:
			# reacquire the lock 
			self._lock.acquire()
开发者ID:Acidburn0zzz,项目名称:pontoon,代码行数:54,代码来源:util.py


示例20: run

 def run(self):
     while True:
         try:
             url_name = urls_queue.get(block=False)
             download_image(*url_name)
         except Empty:
             if self.exit_event.is_set():
                 break
             pass
         except Exception, ex:
             print 'exception in UrlsConsumer:', ex
         threading._sleep(0.1)
开发者ID:vega4,项目名称:FaceSpider,代码行数:12,代码来源:image_baidu_com.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python threading._start_new_thread函数代码示例发布时间:2022-05-27
下一篇:
Python threading._get_ident函数代码示例发布时间: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