本文整理汇总了Python中threading.Timer.is_alive方法的典型用法代码示例。如果您正苦于以下问题:Python Timer.is_alive方法的具体用法?Python Timer.is_alive怎么用?Python Timer.is_alive使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类threading.Timer
的用法示例。
在下文中一共展示了Timer.is_alive方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: exec_node
# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import is_alive [as 别名]
def exec_node(config, execute_with=None):
"""
Executes a node linked with a specific configuration file
:param config: Path of the configuration file
:param execute_with: To run under valgrind, or another program, specify the
path to its executable and optionally some flags to it as a string list.
:return: Returns the node process, the return code and a return message
"""
NODE_BUILD_PATH = "src/node/tchsm_node"
NODE_PATH = join(EXEC_PATH, NODE_BUILD_PATH)
if not isdir(EXEC_PATH):
return None, 1, "ERROR: Path doesn't exists >> " + EXEC_PATH
if not isdir(dirname(NODE_PATH)):
return None, 1, "ERROR: Path doesn't exists >> " + dirname(NODE_PATH)
node = None
try:
if DEBUG:
print(" DEBUG::NODE_CALL: %s" % ' '.join([NODE_PATH, '-c', config + ".conf"]))
args = [NODE_PATH, "-c", config + ".conf"]
if execute_with is not None:
args = execute_with + args
node = subprocess.Popen(args,
stderr=subprocess.PIPE,
stdout=subprocess.PIPE)
except OSError:
return node, 1, "ERROR: Exec could not be accessed >> " + EXEC_PATH + NODE_BUILD_PATH
if node.returncode is not None:
return node, node.returncode, "ERROR: Node finished with return code >> " + str(node.returncode)
timer = Timer(NODE_TIMEOUT * 3, terminate_subprocess, [node])
timer.start()
node_stderr = node.stderr
stderr_lines = iter(node_stderr.readline, "")
for stderr_line in stderr_lines:
stderr_line_decoded = stderr_line.decode()
if DEBUG:
if not (stderr_line_decoded.isspace() or (len(stderr_line) == 0)):
sys.stdout.write(
" DEBUG::STDERR --> " +
stderr_line_decoded)
if NODE_RDY in stderr_line_decoded:
break
if not timer.is_alive():
timer.cancel()
return node, 1, "FAILURE: Node timeout"
if timer.is_alive():
timer.cancel()
return node, 0, ""
else:
return node, -1, "FAILURE: Node didn't exit on time"
示例2: StoreDevice
# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import is_alive [as 别名]
class StoreDevice(GenericDevice):
""" Store """
def __init__(self, channels, name):
GenericDevice.__init__(self, channels, name)
self.name = name
self.type_ = 'Store'
self.exoup = channels['up']['exo']
self.channelup = channels['up']['channel']
self.exodown = channels['down']['exo']
self.channeldown = channels['down']['channel']
self.tmr = Timer( 1, self.exoup.set_output,
[self.channelup, 0])
self.openratio = None
def set_value(self, cmd):
""" Set device status """
if ( cmd == 'up' and
self.exoup.get_output(self.channelup) == 0):
if self.tmr.is_alive():
self.tmr.cancel()
if self.exodown.get_output(self.channeldown) != 0 :
self.exodown.set_output(self.channeldown, 0)
time.sleep(0.3)
self.exoup.set_output(self.channelup, 255)
self.tmr = Timer(30,
self.exoup.set_output, [self.channelup, 0])
self.tmr.start()
if ( cmd == 'down' and
self.exodown.get_output(self.channeldown) == 0):
if self.tmr.is_alive():
self.tmr.cancel()
if ( self.exoup.get_output(self.channelup) != 0 ):
self.exoup.set_output(self.channelup, 0)
time.sleep(0.3)
self.exodown.set_output(self.channeldown, 255)
self.tmr = Timer(30,
self.exodown.set_output, [self.channeldown, 0])
self.tmr.start()
if ( cmd == 'stop' ):
if ( self.tmr.is_alive() ):
self.tmr.cancel()
if ( self.exoup.get_output(self.channelup) !=0 ):
self.exoup.set_output(self.channelup, 0)
elif ( self.exodown.get_output(self.channeldown) != 0 ):
self.exodown.set_output(self.channeldown, 0)
def get_value(self):
""" Get store status """
if ( self.exoup.get_output(self.channelup) != 0 ):
return('up')
elif ( self.exodown.get_output(self.channeldown) !=0 ):
return('down')
else:
return('stop')
示例3: run_onionscan
# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import is_alive [as 别名]
def run_onionscan(onion, identity_lock):
"""
:param onion:
:param identity_lock:
:return:
"""
print("[*] Onionscanning %s" % onion)
# fire up onionscan
process = subprocess.Popen(["/home/clement/.gvm/pkgsets/go1.4/global/bin/onionscan",
"--jsonReport", "--simpleReport=false", onion], stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
# start the timer and let it run 5 minutes
process_timer = Timer(300, handle_timeout, args=[process, onion, identity_lock])
process_timer.start()
# wait for the onion scan results
stdout = process.communicate()[0]
# we have received valid results so we can kill the timer
if process_timer.is_alive():
process_timer.cancel()
return stdout
print("[!!!] Process timed out!")
return None
示例4: TimedRunner
# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import is_alive [as 别名]
class TimedRunner():
def __init__(self, interval, func):
self.time_interval = interval
self.func = func
self.run = True
def start(self):
if self.run:
self.func()
self.thread = Timer(self.time_interval, self.start)
self.thread.start()
else:
self.thread = None
try:
while self.thread and self.thread.is_alive():
self.thread.join(5)
except KeyboardInterrupt:
self.run = False
# Hand the screen back to the terminal
curses.endwin()
# Exit thread
sys.exit()
def cancel(self):
self.thread.cancel()
示例5: MissedMessageWorker
# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import is_alive [as 别名]
class MissedMessageWorker(QueueProcessingWorker):
# Aggregate all messages received over the last BATCH_DURATION
# seconds to let someone finish sending a batch of messages and/or
# editing them before they are sent out as emails to recipients.
#
# The timer is running whenever; we poll at most every TIMER_FREQUENCY
# seconds, to avoid excessive activity.
#
# TODO: Since this process keeps events in memory for up to 2
# minutes, it now will lose approximately BATCH_DURATION worth of
# missed_message emails whenever it is restarted as part of a
# server restart. We should probably add some sort of save/reload
# mechanism for that case.
TIMER_FREQUENCY = 5
BATCH_DURATION = 120
timer_event = None # type: Optional[Timer]
events_by_recipient = defaultdict(list) # type: Dict[int, List[Dict[str, Any]]]
batch_start_by_recipient = {} # type: Dict[int, float]
def consume(self, event: Dict[str, Any]) -> None:
logging.debug("Received missedmessage_emails event: %s" % (event,))
# When we process an event, just put it into the queue and ensure we have a timer going.
user_profile_id = event['user_profile_id']
if user_profile_id not in self.batch_start_by_recipient:
self.batch_start_by_recipient[user_profile_id] = time.time()
self.events_by_recipient[user_profile_id].append(event)
self.ensure_timer()
def ensure_timer(self) -> None:
if self.timer_event is not None:
return
self.timer_event = Timer(self.TIMER_FREQUENCY, MissedMessageWorker.maybe_send_batched_emails, [self])
self.timer_event.start()
def stop_timer(self) -> None:
if self.timer_event and self.timer_event.is_alive(): # type: ignore # Report mypy bug.
self.timer_event.cancel()
self.timer_event = None
def maybe_send_batched_emails(self) -> None:
self.stop_timer()
current_time = time.time()
for user_profile_id, timestamp in list(self.batch_start_by_recipient.items()):
if current_time - timestamp < self.BATCH_DURATION:
continue
events = self.events_by_recipient[user_profile_id]
logging.info("Batch-processing %s missedmessage_emails events for user %s" %
(len(events), user_profile_id))
handle_missedmessage_emails(user_profile_id, events)
del self.events_by_recipient[user_profile_id]
del self.batch_start_by_recipient[user_profile_id]
# By only restarting the timer if there are actually events in
# the queue, we ensure this queue processor is idle when there
# are no missed-message emails to process.
if len(self.batch_start_by_recipient) > 0:
self.ensure_timer()
示例6: StatusSaverService
# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import is_alive [as 别名]
class StatusSaverService(AbstractUserService):
"""
Service which is responsible for scheduling dumping system into file periodically.
"""
autoload = True
#: Dump saving interval, in seconds. Default 30 minutes.
dump_interval = CFloat(30 * 60)
_exit = CBool(False)
_timer = Any(transient=True)
def setup(self):
if self.system.filename:
self.system.on_trait_change(self.exit_save, "pre_exit_trigger")
if self.dump_interval:
self.save_system_periodically()
def save_system_periodically(self):
self.logger.debug('Saving system state')
self.system.save_state()
self._timer = Timer(self.dump_interval, self.save_system_periodically)
self._timer.start()
def exit_save(self):
self.system.save_state()
self._exit = True
def cleanup(self):
if self._timer and self._timer.is_alive():
self._timer.cancel()
示例7: Countdown
# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import is_alive [as 别名]
class Countdown(object):
def __init__ (self, session=None, name=None, start_time=0, total_time=0, sound=None):
assert(total_time > 0)
self.session = session
self.name = name
self.start_time = start_time or time.time()
self.sound = sound or self.session.config['sounds']['countdownFinished']
self.total_time = total_time
self.timer = Timer(total_time, self.countdown_complete)
def start (self):
self.timer.start()
def cancel (self):
if self.timer.is_alive:
self.timer.cancel()
stop = cancel
def remaining_time (self):
return int(self.timer.is_alive()) and self.total_time - (time.time() - self.start_time)
def countdown_complete (self):
self.session.countdowns.remove(self)
output.speak(_("Countdown %s complete.") % self.name, True)
self.play(self.sound)
示例8: _run_multienum
# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import is_alive [as 别名]
def _run_multienum(self):
p = subprocess.Popen([enum_cmd],
stdout=subprocess.PIPE,
stdin=subprocess.PIPE, close_fds=True)
if self.timeout:
timed_out = False
timer = Timer(self.timeout*60, lambda p: p.kill(), [p])
try:
timer.start()
output = p.communicate()[0].decode("utf-8")
finally:
if not timer.is_alive():
timed_out = True
timer.cancel()
if timed_out:
raise TimeoutError('Enumeration took too long.')
else:
output = p.communicate()[0].decode("utf-8")
count = 0
start_count = False
for line in output.strip().split("\n"):
if line.strip().endswith("RunTot"):
start_count = True
elif start_count and re.match(r"\d+\s+.*", line.strip()):
count = int(line.split()[-1])
logger.debug("Enumeration resulted in {} structures".format(count))
return count
示例9: start
# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import is_alive [as 别名]
def start(self):
if self.reporter != None:
timer = Timer(1, self.reporter.start, kwargs={})
self.timer.append(timer)
timer.start()
for watcher in self.observers:
if serviceconfig.isWin32() == True:
timer = Timer(1, watcher.start, kwargs={})
else:
timer = Timer(1, watcher.startScandir, kwargs={})
self.timer.append(timer)
timer.start()
if serviceconfig.isWin32() == True:
for timer in self.timer:
timer.join()
else:
activeThreads = []
for timer in self.timer:
activeThreads.append(timer)
while len(activeThreads) > 0:
for timer in activeThreads:
timer.join(10)
activeThreads = []
for timer in self.timer:
if timer.is_alive():
activeThreads.append(timer)
示例10: startTimer
# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import is_alive [as 别名]
class timer:
def startTimer(self, n, func):
self.stopTimer()
self.t = Timer(n, func)
self.t.start()
def stopTimer(self):
try:
if self.t.is_alive():
self.t.cancel()
except:
pass
示例11: runcode
# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import is_alive [as 别名]
def runcode(code):
try:
tmpdir = tempfile.mkdtemp()
tmpclass = getJavaFileName(code)
if not tmpclass:
print('<span style="color:red">Could not find class name in Java file! Do you have a public class in your code?</span>')
return
if tmpclass == "CustomSecurityManager" or "java" in tmpclass:
print('<span style="color:red">Invalid class name!</span>')
if len(code) > 10000:
print('<span style="color:red">You have too much code! Please limit your code to be less than 10,000 characters.</span>')
return
filename = tmpdir + '/' + tmpclass + '.java'
f = open(filename, 'w')
f.write(code)
f.close()
jenv = os.environ.copy()
appfolder = os.path.dirname(os.path.realpath(__file__))
jars = []
for jar in os.listdir(appfolder + "/web/libs"):
if os.path.isfile(appfolder + "/web/libs/" + jar):
jars.append(appfolder + "/web/libs/" + jar)
shutil.copy(appfolder + "/Wrapper.java", tmpdir + "/Wrapper.java")
p = subprocess.Popen(["javac", "-cp", ".:" + ":".join(jars), "Wrapper.java", filename], cwd=tmpdir, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=jenv)
outdata, errdata = p.communicate()
if p.returncode != 0:
print("<span style='color:red'>Error when compiling!</span>")
if outdata:
print(esc(outdata.decode('utf-8')))
if errdata:
print("<span style='color:red'>" + esc(errdata.decode('utf-8')) + "</span>")
shutil.rmtree(tmpdir)
return
if not os.path.isfile(tmpdir + "/" + tmpclass + ".class"):
print("<span style='color:red'>No class file generated from compile step!</span>")
shutil.rmtree(tmpdir)
return
p = subprocess.Popen(["java", "-Xmx128m", "-cp", ".:" + ":".join(jars), "Wrapper", tmpclass, ":".join([tmpdir, appfolder + "/web/libs/"])], cwd=tmpdir, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=jenv)
timer = Timer(TIMEOUT, p.kill)
timer.start()
outdata, errdata = p.communicate()
if timer.is_alive():
timer.cancel()
shutil.rmtree(tmpdir)
print("<span style='color:green'>Program ran successfully!</span>")
if outdata:
print(esc(outdata.decode('utf-8')))
if errdata:
print("<span style='color:red'>" + esc(errdata.decode('utf-8')) + "</span>")
except Exception as e:
print('<span style="color:red">Unknown error when running code!</span>\n', esc(str(e)))
示例12: CommandManager
# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import is_alive [as 别名]
class CommandManager():
def __init__(self):
self.commandQueue = []
self.myTimer = Timer(0,self.main_loop)
#Creates a new timer an starts it, delay is time until next command
def create_new_timer(self):
sleepTime = max(0,(self.commandQueue[0].executionTime - datetime.now()).total_seconds())
self.myTimer = Timer(sleepTime, self.main_loop)
self.myTimer.start()
#Executes the first command in the commandQueue and removes it from the queue
def execute_command(self):
cmd = self.commandQueue[0]
self.commandQueue.remove(cmd)
cmd.execute()
def main_loop(self):
if len(self.commandQueue) > 0:
self.execute_command()
if len(self.commandQueue) > 0:
self.create_new_timer()
#Enqueue a command object
def enqueue_command(self, newCommand):
newQueue = self.commandQueue
for (i,cmd) in enumerate(newQueue):
if newCommand.executionTime < cmd.executionTime:
newQueue.insert(i, newCommand)
#if insert at start
if i==0:
self.myTimer.cancel()
self.create_new_timer()
break
else:
newQueue.append(newCommand)
if not self.myTimer.is_alive():
self.create_new_timer()
self.commandQueue = newQueue
#Delete a command, resets timer aswell
def delete_command(self,cmdId):
cmdToRemove = self.commandQueue[cmdId]
self.commandQueue.remove(cmdToRemove)
if len (self.commandQueue) > 0:
self.create_new_timer()
示例13: PerpetualTimer
# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import is_alive [as 别名]
class PerpetualTimer(object):
"""A timer wrapper class that repeats itself.
"""
def __init__(self, t, handler):
self.t = t
self.handler = handler
self.thread = Timer(self.t, self.handle_function)
def handle_function(self):
self.handler()
self.thread = Timer(self.t, self.handle_function)
self.thread.setDaemon(True)
self.thread.start()
def start(self):
self.thread.start()
def cancel(self):
if self.thread.is_alive():
self.thread.cancel()
示例14: get_list_pkg_upgrades
# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import is_alive [as 别名]
def get_list_pkg_upgrades(module, timeout):
cmd = "sudo aptitude -s -y upgrade"
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True, preexec_fn=os.setsid)
t = Timer(timeout, kill_procgroup, [p])
t.start()
output, err = p.communicate()
if t.is_alive():
t.cancel()
else:
error_msg = "Timeout on cmd %s output %s" % (cmd, output)
module.fail_json(msg=error_msg)
if p.returncode != 0:
error_msg = "Failed to run %s" % (cmd)
module.fail_json(msg=error_msg)
output = output.splitlines()
list_pkg_upgrades = []
UPGRADE_STR="The following packages will be upgraded:"
RECOMMEND_STR="The following packages are RECOMMENDED but will NOT be installed:"
idx_start_match = next((i for i, v in enumerate(output) if v == UPGRADE_STR), -1)
if idx_start_match == -1:
return list_pkg_upgrades
idx_end_match = next((i for i, v in enumerate(output) if v == RECOMMEND_STR), -1)
if idx_end_match == -1:
idx_end_match = next((i for i, v in enumerate(output) if re.match('^\d*\s*packages upgraded.*not upgraded.$',v)), -1)
if idx_end_match == -1:
return list_pkg_upgrades
for line in output[idx_start_match+1:idx_end_match]:
list_pkg_upgrades.extend(line.split())
for pkg in list_pkg_upgrades:
print "Pkg: %s" % pkg
return list_pkg_upgrades
示例15: run_onionscan
# 需要导入模块: from threading import Timer [as 别名]
# 或者: from threading.Timer import is_alive [as 别名]
def run_onionscan(onion):
print "[*] Onionscanning %s" % onion
# fire up onionscan
process = subprocess.Popen(["onionscan","--webport=0","--jsonReport","--simpleReport=false",onion],stdout=subprocess.PIPE,stderr=subprocess.PIPE)
# start the timer and let it run 5 minutes
process_timer = Timer(300,handle_timeout,args=[process,onion])
process_timer.start()
# wait for the onion scan results
stdout = process.communicate()[0]
# we have received valid results so we can kill the timer
if process_timer.is_alive():
process_timer.cancel()
return stdout
print "[!!!] Process timed out!"
return None