[英]Setting a countdown timer for a function in Python
我需要設置一個倒數計時器(2 分鍾),以便第一次初始化函數獲得回調(它將在 2 分鍾內不斷獲得回調)。 當 2 分鍾結束時,重置計時器並執行其他操作,當我的“主”函數結束時,等待來自 clipboard_monitor.on_text() 的新觸發器,以便再次為初始化函數設置倒數計時器。 這一切都可能嗎?
代碼:
import clipboard_monitor
class ABC():
def __init__(self):
.....
.....
def initialize(url):
run = ABC()
toDo.append(url)
# What I ideally want is to print the message bellow with a counter of how many times this
# function has been called
print("URL has been added to queue for download.")
# For every element in the list.
for x in toDo:
# main() is another function I have that I am using what I got from the clipboard.
run.main(x)
# if the last element reached empty list and exit loop
if x == toDo[-1]:
toDo = [""]
break
.....
.....
def main(self, url):
.....
.....
clipboard_monitor.on_text(ABC.initialize)
clipboard_monitor.wait()
謝謝
你可以像這樣使用時間模塊:
import time
class countdown_timer():
def __init__(self):
self.time_end = 0
self._is_running = False
self.start_time = None
def start(self, countdown_time):
self.start_time = time.time()
self.time_end = countdown_time
self._is_running = True
def get_time(self):
if time.time() - self.start_time >= self.time_end:
self._is_running = False
if self._is_running:
return self.time_end - (time.time() - self.start_time)
else:
return 0
def is_running(self):
if time.time() - self.start_time >= self.time_end:
self._is_running = False
return self._is_running
並像這樣使用它:
timer1 = countdown_timer() # create the timer
timer1.start(120) # start the timer
timer1.get_time() # return number of seconds until timer as reach 0
timer1.is_running() # return True if timer is running, False if time have reach 0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.