本文整理汇总了Python中threading.Timer方法的典型用法代码示例。如果您正苦于以下问题:Python threading.Timer方法的具体用法?Python threading.Timer怎么用?Python threading.Timer使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类threading
的用法示例。
在下文中一共展示了threading.Timer方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: run
# 需要导入模块: import threading [as 别名]
# 或者: from threading import Timer [as 别名]
def run(port=None):
import webbrowser, threading
if port is None:
port = getRandomPort()
# load()
url = "http://127.0.0.1:{}/".format(port)
logging.info("Starting browser at {}".format(url))
# webbrowser.open_new(url)
threading.Timer(1.25, lambda: webbrowser.open(url) ).start()
app.run(
port=port#,
# debug=True
)
示例2: test_reloader_live
# 需要导入模块: import threading [as 别名]
# 或者: from threading import Timer [as 别名]
def test_reloader_live(runargs, mode):
with TemporaryDirectory() as tmpdir:
filename = os.path.join(tmpdir, "reloader.py")
text = write_app(filename, **runargs)
proc = Popen(argv[mode], cwd=tmpdir, stdout=PIPE, creationflags=flags)
try:
timeout = Timer(5, terminate, [proc])
timeout.start()
# Python apparently keeps using the old source sometimes if
# we don't sleep before rewrite (pycache timestamp problem?)
sleep(1)
line = scanner(proc)
assert text in next(line)
# Edit source code and try again
text = write_app(filename, **runargs)
assert text in next(line)
finally:
timeout.cancel()
terminate(proc)
with suppress(TimeoutExpired):
proc.wait(timeout=3)
示例3: __init__
# 需要导入模块: import threading [as 别名]
# 或者: from threading import Timer [as 别名]
def __init__(self, sync_unread=False):
self.auth_token = read_token()
if self.auth_token is None:
self.auth_token = login()
try:
write_token(self.auth_token)
except IOError:
pass
self.jike_session = JikeSession(self.auth_token)
self.collection = None
self.news_feed = None
self.following_update = None
self.unread_count = 0
self.timer = None
if sync_unread:
self.timer = Timer(
CHECK_UNREAD_COUNT_PERIOD,
check_unread_count_periodically,
args=(self,)
).start()
self.notified_topics = ['all']
self.notified_users = ['all']
示例4: stop_button_cmd
# 需要导入模块: import threading [as 别名]
# 或者: from threading import Timer [as 别名]
def stop_button_cmd():
"""
Stop button click handler
"""
# Do some routines for stopping calculation
calculation_stop()
# Stop algorithm's process
search_process.terminate()
output_pipe.close()
# Stop timer thread and stop refreshing status bar
timer_event.set()
# Clear status labels
threading.Timer(0.1, max_ram_var.set, args=('',)).start()
threading.Timer(0.1, cpu_var.set, args=('',)).start()
threading.Timer(0.1, ram_var.set, args=('',)).start()
# Action buttons
#
# Output stop widget and it's border frame
示例5: FoundANewCoinEvent
# 需要导入模块: import threading [as 别名]
# 或者: from threading import Timer [as 别名]
def FoundANewCoinEvent(newCoin):
global E_MODE
global PURCHARSED_COIN_NAME
print("FoundANewCoinEvent(newCoin)")
E_MODE = 1 # change mode into TRADING
onlyEngCoinName = re.sub(r"[^A-Za-z]+", '', newCoin)
sendTelegramMsg("새로운 코인 상장 발견 : " + newCoin +", [" + onlyEngCoinName +"]로 비트렉스 시장 검색시작.")
# buy 95% of current balance at bittrex
affordable, savedRate= HowManyCoinYouCanBuyWithMyBalance("BTC", onlyEngCoinName)
targetCoinName, Quantity_request= BuyLimit_PercentageOfMyBalance("BTC", onlyEngCoinName, affordable, savedRate, 0.95)
PURCHARSED_COIN_NAME = targetCoinName # save purchased name of coin
sendTelegramMsg("[" + targetCoinName +"]코인을 " + str(Quantity_request) +"만큼 매수 시도했음.")
t = Timer(600, SellAgain)
t.start() # after x seconds, sell again
示例6: FoundLeadingSignal
# 需要导入模块: import threading [as 别名]
# 或者: from threading import Timer [as 别名]
def FoundLeadingSignal(TargetCoinName):
global E_MODE
global PURCHARSED_COIN_NAME
# buy 95% of current balance at bittrex
affordable, savedRate= HowManyCoinYouCanBuyWithMyBalance("BTC", TargetCoinName)
_targetCoinName, Quantity_request, Price_request, err_msg= BuyLimit_PercentageOfMyBalance("BTC", TargetCoinName, affordable, savedRate, 0.95)
if savedRate == None:
sendTelegramMsg("[" + _targetCoinName +"]코인을 구매하는데 실패했음. \nbittrex에 없는 코인일 가능성 확인바람.")
else:
if Quantity_request == 0:
sendTelegramMsg("[" + _targetCoinName +"]코인을 구매하는데 실패했음. \n에러명 : " + err_msg + "\n그래도 sell limit 시도는 함.")
else:
PURCHARSED_COIN_NAME = _targetCoinName # save purchased name of coin
sendTelegramMsg("[" + _targetCoinName +"]코인을 " + str(Quantity_request) +"만큼 매수 시도했음. \n매수 시도 가격 : {0:.8f}".format(Price_request))
# normally, 80secs to 100secs go high
t = Timer(90, SellAgain)
t.start() # after x seconds, sell again
示例7: GvizTableData
# 需要导入模块: import threading [as 别名]
# 或者: from threading import Timer [as 别名]
def GvizTableData(request):
"""Returns a string formatted for consumption by a Google Viz table."""
#def throw_deadline():
# logging.info('MANUAL THROW!! DeadlineExceededError DeadlineExceededError')
# raise DeadlineExceededError
#t = Timer(15.0, throw_deadline)
test_set = None
category = request.GET.get('category')
if not category:
return http.HttpResponseBadRequest('Must pass category=something')
test_set = all_test_sets.GetTestSet(category)
if not test_set:
return http.HttpResponseBadRequest(
'No test set was found for category=%s' % category)
formatted_gviz_table_data = GetStats(request, test_set, 'gviz_table_data')
return http.HttpResponse(formatted_gviz_table_data)
示例8: run
# 需要导入模块: import threading [as 别名]
# 或者: from threading import Timer [as 别名]
def run(cmd, timeout, verbose):
if verbose:
sto = None
ste = None
else:
devnull = open(os.devnull, 'w')
sto = devnull
ste = devnull
# Alternative without timeout
# subprocess.run(cmd, shell=True, stdout=sto, stderr=ste)
proc = Popen(shlex.split(cmd), stdout=sto, stderr=ste)
timer = Timer(timeout, proc.kill)
try:
timer.start()
proc.communicate()
finally:
if proc.poll() != 0:
raise TimeoutExpired('Command `{}` timed out'.format(cmd))
timer.cancel()
示例9: PostWarmup
# 需要导入模块: import threading [as 别名]
# 或者: from threading import Timer [as 别名]
def PostWarmup(self):
# check to see if the generator is running
status = self.SendCommand("generator: getbase")
if not status.lower() in ["running", "exercising"]:
self.LogError("WARNING: generator not running post warmup. Transfer switch not activated.")
self.SendCommand("generator: setremote=stop")
return
self.SendCommand("generator: setremote=starttransfer")
self.DebugOutput("Starting transfer exercise cycle (post warmup).")
# set timer to stop
self.StopTimer = threading.Timer(float(self.ExerciseDuration * 60.0), self.StopExercise)
self.StopTimer.start()
# ---------- GenExercise::ReadyToExercise-----------------------------------
示例10: poll_target
# 需要导入模块: import threading [as 别名]
# 或者: from threading import Timer [as 别名]
def poll_target(self, *kwargs):
log.info("Poll target")
if self.state.wait_target_state == dbg.TARGET_STATE_STOPPED:
stopped,rsn_str = self.is_stopped()
if stopped:
self.state.wait_target_state = dbg.TARGET_STATE_UNKNOWN
self.__command_processor.generate_StoppedEvent(reason=rsn_str,
thread_id=0,
all_threads_stopped=True)
elif self.state.wait_target_state == dbg.TARGET_STATE_RUNNING:
# this is not fully implemented yet, need to define when we need to start waiting for target get running
try:
self._gdb.wait_target_state(dbg.TARGET_STATE_RUNNING, 0)
self.state.wait_target_state = dbg.TARGET_STATE_UNKNOWN
self.__command_processor.generate_ContinuedEvent(thread_id=0,
all_threads_continued=True)
except dbg.DebuggerTargetStateTimeoutError:
pass
if self.state.wait_target_state != dbg.TARGET_STATE_UNKNOWN:
# restart timer if we still need to wait for target state
self.target_poller = threading.Timer(1.0, self.poll_target, args=[self,])
self.target_poller.start()
示例11: __init__
# 需要导入模块: import threading [as 别名]
# 或者: from threading import Timer [as 别名]
def __init__(self, input_channel, serial_physical_obj):
#Initialize class variables
self.rx_packet_queue = Queue.Queue()
self.rx_data_payload_queue = Queue.Queue()
self.logic_startbyte_received = False
self.logic_escapebyte_received = False
self.logic_stopbyte_received = False
self.receiver_class = Receiver_Datalink_Device_State_Parser_Class(input_channel, serial_physical_obj)
self.enable_flag = True
self.max_payload_size = 6
self.datalink_packet_format = 'c' + str(self.max_payload_size) + 'c' + 'c'
self.reconstruct_data = ''
self.timer_interval = 5
self.timer = threading.Timer(self.timer_interval, self.timer_trip)
self.datalink_packet_struct = struct.Struct('BBB125s')
#Start
threading.Thread.__init__(self)
self.start() #Starts the run() function and thread
示例12: note
# 需要导入模块: import threading [as 别名]
# 或者: from threading import Timer [as 别名]
def note(frequency, duration=1.0):
"""Play a single note.
:param frequency: Musical frequency in hertz
:param duration: Optional duration in seconds, use None to sustain note
"""
global _timeout
setup()
if frequency <= 0:
raise ValueError("Frequency must be > 0")
if duration is not None and duration <= 0:
raise ValueError("Duration must be > 0")
clear_timeout()
pwm.ChangeFrequency(frequency)
GPIO.setup(BUZZER, GPIO.OUT)
if duration is not None and duration > 0:
_timeout = Timer(duration, stop)
_timeout.start()
示例13: execWait
# 需要导入模块: import threading [as 别名]
# 或者: from threading import Timer [as 别名]
def execWait(cmd, outfile=None, timeout=0):
result = ""
env = os.environ
proc = subprocess.Popen(cmd, executable='/bin/bash', env=env, stderr=subprocess.STDOUT, stdout=subprocess.PIPE, shell=True)
if timeout:
timer = threading.Timer(timeout, proc.kill)
timer.start()
result = proc.communicate()[0]
if timeout:
if timer.is_alive():
timer.cancel()
if outfile:
if Utils.fileExists(outfile):
print "FILE ALREADY EXISTS!!!!"
else:
tmp_result = "\033[0;33m(" + time.strftime(
"%Y.%m.%d-%H.%M.%S") + ") <pentest> #\033[0m " + cmd + Utils.newLine() + Utils.newLine() + result
Utils.writeFile(tmp_result, outfile)
return result
示例14: work_analog
# 需要导入模块: import threading [as 别名]
# 或者: from threading import Timer [as 别名]
def work_analog():
threading.Timer(rate_ana, work_analog).start()
SignalK='{"updates":[{"$source":"OPsensors.SPI.MCP3008","values":[ '
Erg=''
send=False
for i in MCP:
if i[0]==1:
send=True
XValue=read_adc(i[1])
if i[4]==1:
XValue = interpolread(i[1],XValue)
Erg +='{"path": "'+i[2]+'","value":'+str(XValue)+'},'
if send:
SignalK +=Erg[0:-1]+']}]}\n'
sock.sendto(SignalK, ('127.0.0.1', 55557))
# read gpio and GENERATE SK
示例15: Update
# 需要导入模块: import threading [as 别名]
# 或者: from threading import Timer [as 别名]
def Update(self):
# Get our wake-up thread ready...
self.ticker = threading.Timer(self.INTERVAL, self.Update)
try:
# Check if any of our topics have new info to pass on
if len(self.topics):
refresh = False
for topic in self.topics.itervalues():
topic.Update(self)
if topic.HasChanged():
refresh = True
topic.Reset()
if refresh:
self.SignalExcel()
finally:
self.ticker.start() # Make sure we get to run again