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


Python Timer.isAlive方法代码示例

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


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

示例1: newfunc

# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import isAlive [as 别名]
 def newfunc(*arg, **kwargs):
     timer = Timer(limit, handler)
     try:
         log.debug('starting timer in %s for %s', 
             str(datetime.datetime.now()), str(limit))
         timer.start()
         ret = func(*arg, **kwargs)
     except KeyboardInterrupt:
         if timer.isAlive:
             timer.cancel()
         raise
     except:
         if timer.isAlive():
             timer.cancel()
             log.debug('canceled timer in %s because of failure', 
                 str(datetime.datetime.now()))
             raise
         else:
             raise TimeExpired, 'Time expired ( and test raised: ' \
                 + str(sys.exc_info()) + ')', sys.exc_info()[2]
     if timer.isAlive():
         timer.cancel()
         log.debug('canceled timer in %s', str(datetime.datetime.now()))
     else:
         log.debug('timer has expired', str(datetime.datetime.now()))
         raise TimeExpired("time limit exceeded")
     return ret
开发者ID:snua12,项目名称:zlomekfs,代码行数:29,代码来源:timeoutPlugin.py

示例2: startTimer

# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import isAlive [as 别名]
class timer:
      
      # start timer with n seconds and go to self.timerExpired
      def startTimer(self, n):
        self.t = Timer(n, self.timerExpired)
        print 'Timer started for %d seconds'% n
        
        #start the timer instance
        self.t.start()
        
      # Called if argument is true to stop it.
      def stopTimer(self):
        
        # First look if the timer is active
        if self.t.isAlive():
                print 'Timer found active'
                
                #Stop the timer instance
                self.t.cancel()
                print 'Timer stopped'
        
        # If not active, do nothing
        else:
                print 'Timer inactive'
                
      # Put code in here to execute after timer has expired.
      def timerExpired(self):
        print 'Timer expired, go to do what you want'
开发者ID:bhramoss,项目名称:code,代码行数:30,代码来源:recipe-440476.py

示例3: __init__

# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import isAlive [as 别名]
class CustomTimer:
    def __init__(self, value, f):
        self.timer = Timer(value, f)
        self.f = f

    def reset(self, value):
        if not self.timer.isAlive():
            raise CustomTimerException("don't reset when timer not started")
        self.timer.cancel()
        self.timer = Timer(value, self.f)
        self.timer.start()

    def start(self):
        if self.timer.isAlive():
            raise CustomTimerException("don't start a timer when he's already up")
        self.timer.start()
开发者ID:guillaumeb0,项目名称:objets_communicants,代码行数:18,代码来源:custom_timer.py

示例4: LCD_SM

# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import isAlive [as 别名]
class LCD_SM(StateMachine):
    def __init__(self, cad):
        # Initial state
        self.cad = cad
        self.parser = ConfigParser()
        self.configFile = '/home/pi/projects/PiFace/config.ini'
        self.parser.read(self.configFile)

        # Static variable initialization:
        LCD_SM.waiting = Waiting(cad, self)
        LCD_SM.menu = Menu(cad, self)
        LCD_SM.sections = Sections(cad, self)
        LCD_SM.options = Options(cad, self)
        LCD_SM.editing = Editing(cad, self)
        LCD_SM.scanning = Scanning(cad, self)
        
        StateMachine.__init__(self, LCD_SM.waiting)
        self.currentState = self.currentState.run()

        #Timer used to turn off display when inactive for
        self.t = Timer(INACTIVE_TIME, self.hibernate)

    def run(self, event):
        self.currentState = self.currentState[0].next(event.pin_num)

        #If a button has been pressed the program will be directed
        #here. Cancel the current timer and start a new timer
        if self.t.isAlive():
            self.t.cancel()
            self.t.join()
        if not self.t.isAlive():
            self.t = Timer(INACTIVE_TIME, self.hibernate)
            self.t.start()

        #The Waiting.run state does not require any arguments 
        if (len(self.currentState)>1):
            self.currentState[0].run(self.currentState[1])
        else:
            self.currentState[0].run()

    def hibernate(self):
        #If inactive put the display in waiting state
        self.currentState = LCD_SM.waiting.run()
        self.t.cancel()
开发者ID:frellwan,项目名称:SciFy-Pi,代码行数:46,代码来源:lcdSM.py

示例5: PandaPlayer

# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import isAlive [as 别名]
class PandaPlayer(xbmc.Player):

	def __init__(self, core=None, panda=None):
		#xbmc.Player.__init__(self, xbmc.PLAYER_CORE_MPLAYER)
		#xbmc.Player.__init__(self, xbmc.PLAYER_CORE_AUTO)
		xbmc.Player.__init__(self)
		self.panda = panda
		self.timer = None

	def playSong(self, item):
		self.play(item[0], item[1])

	def play(self, url, item):
		xbmc.Player(xbmc.PLAYER_CORE_MPLAYER).play(url, item)
		#xbmc.Player(xbmc.PLAYER_CORE_AUTO).play(url, item)

	def onPlayBackStarted(self):
		print "PANDORA: onPlayBackStarted: %s" % self.getPlayingFile()
		if self.panda.playing:
			'''if not "pandora.com" in self.getPlayingFile():
				self.panda.playing = False
				self.panda.quit()
			else:
				#Show Visualization (disappears after each song...)'''
			xbmc.executebuiltin("ActivateWindow( 12006 )")

	def onPlayBackEnded(self):
		print "PANDORA: onPlayBackEnded"
		self.stop()
		print "PANDORA: playing = %s" % self.panda.playing
		if self.timer and self.timer.isAlive():
			self.timer.cancel()
		if self.panda.skip:
			self.panda.skip = False
		if self.panda.playing:
			self.timer = Timer(0.5, self.panda.playNextSong)
			self.timer.start()

	def onPlayBackStopped(self):
		print "PANDORA: onPlayBackStopped"
		self.stop()
		print "PANDORA: playing = %s" % self.panda.playing
		if self.timer and self.timer.isAlive():
			self.timer.cancel()

                #catch for if this was actually a skip
                if self.panda.playing and self.panda.skip:
                        self.panda.skip = False
                        self.timer = Timer(0.5,self.panda.playNextSong)
                        self.timer.start()
                else:
                        if xbmc.getCondVisibility('Skin.HasSetting(PandoraVis)'):
                                xbmc.executebuiltin('Skin.Reset(PandoraVis)')
                        self.panda.Quit()
开发者ID:danekasper,项目名称:script.xbmc.pandorajson,代码行数:56,代码来源:pandaplayer.py

示例6: runQuery

# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import isAlive [as 别名]
def runQuery(txn, sql, columns, dbapi, timeout):
    """
    execute a sql query.

    @param txn: database cursor
    @type txn: dbapi.cursor or adbapi.Transaction
    @param sql: sql operation
    @type sql: string
    @param columns: columns to return
    @type columns: list
    @param dbapi: dbapi module to use
    @type dbapi: module
    @param timeout: timeout in seconds
    @type timeout: int
    """
    def _timeout(txn):
        if isinstance(txn, dbapi.Transaction):
            cursor = txn._cursor
            connection = txn._connection
        else:
            cursor = txn
            connection = getattr(cursor, 'connection', lambda:None)()
        if hasattr(connection, 'cancel'):
            connection.cancel()
        cursor.close()
    def _convert(val, type):
        if val is None:
            if type == dbapi.STRING:
                return ''
            if type == dbapi.NUMBER:
                return 0
            return None
        if val and type == dbapi.NUMBER:
            return float(val)
        if type == dbapi.STRING:
            return str(val).strip()
        return val
    res = []
    t = Timer(timeout, _timeout, txn)
    t.start()
    try:
        for q in re.split('[ \n]go[ \n]|;[ \n]', sql, re.I):
            if not q.strip(): continue
            txn.execute(q.strip())
    except Exception, ex:
        if t.isAlive():
            t.cancel()
        else:
            ex = TimeoutError('Query Timeout')
        raise ex
开发者ID:alienth,项目名称:ZenPacks.community.SQLDataSource,代码行数:52,代码来源:SQLClient.py

示例7: PandaPlayer

# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import isAlive [as 别名]
class PandaPlayer( xbmc.Player ):

	def __init__( self, core=None, panda=None ):
		xbmc.Player.__init__( self, xbmc.PLAYER_CORE_MPLAYER )
		self.panda = panda
		self.timer = None

	def playSong( self, item ):
		print "PANDORA: Item 0 %s" % item[0]
		print "PANDORA: Item 1 %s" % item[1]
		self.play( item[0], item[1] )

	def play( self, url, item ):
		xbmc.Player(xbmc.PLAYER_CORE_MPLAYER).play( url, item )

	def onPlayBackStarted( self ):
		print "PANDORA: onPlayBackStarted: %s" %self.getPlayingFile()
		if self.panda.playing:
			if not "pandora.com" in self.getPlayingFile():
			    if not "p-cdn.com" in self.getPlayingFile():
				self.panda.playing = False
				self.panda.quit()
			else:
				#Show Visualization (disappears after each song...)
				xbmc.executebuiltin( "ActivateWindow( 12006 )" )

	def onPlayBackEnded( self ):
		print "PANDORA: onPlayBackEnded"
		self.stop()
		print "PANDORA: playing = %s" %self.panda.playing
		if self.timer and self.timer.isAlive():
			self.timer.cancel()
		if self.panda.skip:
			self.panda.skip = False
		if self.panda.playing:
			self.timer = Timer( 0.5, self.panda.playNextSong )
			self.timer.start()

	def onPlayBackStopped( self ):
		print "PANDORA: onPlayBackStopped"
		self.stop()
		print "PANDORA: playing = %s" %self.panda.playing
		if self.timer and self.timer.isAlive():
			self.timer.cancel()
		if self.panda.playing:
			if self.panda.skip:
				self.panda.skip = False
			self.timer = Timer( 0.5, self.panda.playNextSong )
			self.timer.start()
开发者ID:XDoKToR,项目名称:repository.k3oni.xbmc-addons,代码行数:51,代码来源:pandaplayer.py

示例8: main

# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import isAlive [as 别名]
def main(stdscr):
	drawScreen(stdscr)

	stdscr.nodelay(True)

	t = Timer(5.0, drawSongs,args=[stdscr,])
	t.start()

	fullScreenTimer=Timer(60.0, drawScreen,args=[stdscr,])
	fullScreenTimer.start()

	x='blank'
	while x!='qq':
		try:
			if x!='blank':
				x=str(x) + str(stdscr.getkey(4,16))
				selectedSongNumber=int(x)-1

				if selectedSongNumber<100:
					addSong(stdscr,selectedSongNumber)
				x='blank'
			else:
				x=stdscr.getkey(4,15)

		except:
			if t.isAlive() == False:
				# logging.debug("Exception getting key\n")
				# logging.debug("t is alive: " + str(t.isAlive()) + "\n")
				t = Timer(7.0, drawSongs,args=[stdscr,])
				t.start() # after 5 seconds
			if fullScreenTimer.isAlive()==False:
				fullScreenTimer=Timer(60.0, drawScreen,args=[stdscr,])
				fullScreenTimer.start()
			pass

	stdscr.keypad(0);
开发者ID:DigitalHarborFoundation,项目名称:piJukebox,代码行数:38,代码来源:piJukebox.py

示例9: __init__

# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import isAlive [as 别名]
class Player:
    def __init__(self, state):
        state.addObserver(self)
        self.currClip = None
        self.timer = None
        self.output = Output()
        self.state = state
        self.audioFile = None
        self.converter = None
        self.mp3file = None

    def update(self, observable, *args):
        # print "player: updates"

        if observable.currClip != self.currClip:
            self.stop()
            self.currClip = observable.currClip
            self.loadAudioFile()

        if observable.isPaused and self.output.isPlaying:
            self.stop()

        if not observable.isPaused and not self.output.isPlaying:
            self.play()

    def play(self):
        # print "is playing"
        self.timer = Timer(self.currClip[1] - float(self.audioFile.pos),
                           self.atEndOfFile)
        self.output.play(self.audioFile, self.converter)
        self.timer.start()

    def stop(self):
        if self.timer and self.timer.isAlive():
            self.timer.cancel()
        self.output.stop()

    def loadAudioFile(self):
        if self.mp3file != self.currClip[2]:
            self.mp3file = self.currClip[2]
            self.audioFile = AudioFile(self.mp3file)
        self.audioFile.pos = self.currClip[0]
        self.converter = Converter(self.audioFile,
                                   self.output)

    def atEndOfFile(self):
        self.output.stop()
        self.state.skip()
开发者ID:Neppord,项目名称:daisy-delight,代码行数:50,代码来源:player.py

示例10: PeriodicTimer

# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import isAlive [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()
        self.timer = Timer(self.frequency, self._check_for_event, ())
        return self.frequency

    def action(self, action, *action_args, **kwargs):
        self._action = action
        self._action_args = action_args
        self._action_kwargs = kwargs

    def start(self):
        self.is_stopped.clear()
        if not self.timer.isAlive():
            self.timer.start()

    def stop(self):
        self.is_stopped.set()

    def _check_for_event(self):
        while not self.is_stopped.isSet():
            if self.is_stopped.isSet():
                break
            if self._action:
                self._action(*self._action_args, **self._action_kwargs)
            else:
                self.stop()
            # Handle not so graceful shutdown
            try:
                self.is_stopped.wait(self.frequency)
            except:
                pass
开发者ID:ssteinerx,项目名称:pytomation,代码行数:48,代码来源:periodic_timer.py

示例11: run_module

# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import isAlive [as 别名]
    def run_module(self, port):

        t = Timer(5.0, self.__check_module_state)
        t.start()

        vectors = self._get_default_vector2()
        if not vectors:
            vectors  = self.vectors.get_vectors_by_interpreters(self.modhandler.loaded_shells)
        for vector in vectors:
            
            self.last_vector = vector.name
            self.__execute_payload(vector, [port])

        if t.isAlive():
            t.cancel()
            
        if not self.done:
            self.last_vector = None
            self.mprint("[%s] No backdoor method worked. Assure port is not busy." % (self.name))
开发者ID:BaldyBadgersRunningRoundMyBrain,项目名称:weevils,代码行数:21,代码来源:tcp.py

示例12: run_module

# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import isAlive [as 别名]
    def run_module(self, port):

        t = Timer(5.0, self.__check_module_state)
        t.start()

        vectors = self._get_default_vector2()
        if not vectors:
            vectors  = self.vectors.get_vectors_by_interpreters(self.modhandler.loaded_shells)
        for vector in vectors:
            
            self.last_vector = vector.name
            self.__execute_payload(vector, [port])

        if t.isAlive():
            t.cancel()
            
        if not self.done:
            self.last_vector = None
            self.mprint("[%s] No vector works. Check port '%i' availability and privileges" % (self.name, port))
开发者ID:h3rucutu,项目名称:weevely-old,代码行数:21,代码来源:tcp.py

示例13: run_module

# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import isAlive [as 别名]
    def run_module(self, host, port):

        t = Timer(5.0, self.__check_module_state)
        t.start()

        vectors = self._get_default_vector2()
        if not vectors:
            vectors  = self.vectors.get_vectors_by_interpreters(self.modhandler.loaded_shells)
        for vector in vectors:
            
            self.last_vector = vector.name
            self.__execute_payload(vector, [host, port])

        if t.isAlive():
            t.cancel()
            
        if not self.done:
            self.last_vector = None
            self.mprint("[%s] No reverse backdoor method worked. Assure remote port is" % (self.name))
            self.mprint("[%s] listening using commands like \'nc -v -l -p <port>\'" % (self.name))
开发者ID:BaldyBadgersRunningRoundMyBrain,项目名称:weevils,代码行数:22,代码来源:reverse_tcp.py

示例14: runWithArguments

# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import isAlive [as 别名]
 def runWithArguments(self, arguments, timeout=10):
     """
     Execute test script with arguments.
     """
     test_file = os.path.join(
         os.path.dirname(__file__), 'helper_sys_argv.py')
     command = [sys.executable, test_file]
     command.extend(arguments)
     proc = subprocess.Popen(
         command,
         stdout=subprocess.PIPE,
         stderr=subprocess.PIPE,
         )
     timer = Timer(timeout, lambda p: p.kill(), [proc])
     timer.start()
     stdout, stderr = proc.communicate()
     timer.cancel()
     timer.join(timeout=10)
     if timer.isAlive():
         raise AssertionError('Timeout thread is still alive.')
     return stdout, stderr
开发者ID:chevah,项目名称:compat,代码行数:23,代码来源:test_nt_unicode_argv.py

示例15: runCommandPopenCommunicate

# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import isAlive [as 别名]
def runCommandPopenCommunicate(command, shell_True, timeout_sec_None, print_comand_True):
    run_successfully = False
    if not isinstance(command, basestring):
        command = ' '.join(command)
    command = shlex.split(command)

    if print_comand_True:
        print 'Running: ' + ' '.join(command)

    if shell_True:
        command = ' '.join(command)
        proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
    else:
        proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

    not_killed_by_timer = True
    if timeout_sec_None is None:
        stdout, stderr = proc.communicate()
    else:
        timer = Timer(timeout_sec_None, kill_subprocess_Popen, args=(proc, command,))
        timer.start()
        stdout, stderr = proc.communicate()
        timer.cancel()
        not_killed_by_timer = timer.isAlive()

    if proc.returncode == 0:
        run_successfully = True
    else:
        if not print_comand_True and not_killed_by_timer:
            print 'Running: ' + str(command)
        if len(stdout) > 0:
            print 'STDOUT'
            print stdout.decode("utf-8")
        if len(stderr) > 0:
            print 'STDERR'
            print stderr.decode("utf-8")
    return run_successfully, stdout, stderr
开发者ID:INNUENDOCON,项目名称:INNUca,代码行数:39,代码来源:utils.py


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