我有這個作業代碼,考慮到當地時間,每 3 分鐘檢查一次條件,所以每 0、3、6、9 ......它列印“檢查條件”。
import time
def get_next_time():
minute = time.localtime().tm_min
result = 3 - (minute % 3) minute
if result == 60:
result = 0
return result
next_run = get_next_time()
while True:
now = time.localtime()
if next_run == now.tm_min:
print("checking condition")
#some condition
next_run = get_next_time()
time.sleep(1)
問題是我需要沒有函式的代碼,所以我需要找到一種不使用任何函式來撰寫這段代碼的方法,并且我不能使用 break 或 interrput 回圈
我試過了:
while True:
minute = time.localtime().tm_min
result = 3 - (minute % 3) minute
if result == 60:
result = 0
now = time.localtime()
if result == now.tm_min:
print("checking conditions")
time.sleep(1)
但它不起作用:它什么也不做。有任何想法嗎?
uj5u.com熱心網友回復:
您可以在一個陳述句中壓縮函式:
import time
next_run = (3 - (time.localtime().tm_min % 3) time.localtime().tm_min)%60
while True:
now = time.localtime()
if next_run == now.tm_min:
print("checking condition")
#checking conditions...
next_run=(3 - (time.localtime().tm_min % 3) time.localtime().tm_min)%60
time.sleep(1)
uj5u.com熱心網友回復:
第一次,get_next_time()只會在 時執行next_run == now.tm_min。第二次,你在每個回圈中執行它
import time
minute = time.localtime().tm_min
result = 3 - (minute % 3) minute
if result == 60:
result = 0
while True:
now = time.localtime()
if result == now.tm_min:
print("checking conditions")
minute = time.localtime().tm_min
result = 3 - (minute % 3) minute
if result == 60:
result = 0
time.sleep(1)
uj5u.com熱心網友回復:
四舍五入到下一個 3 分鐘的倍數與規范“每 0...”相矛盾。
做就夠了
import time
first= True
while True:
minute= time.localtime().tm_min
if first or minute == target:
print("checking condition")
first= False
target= (minute 3) % 60
time.sleep(1)
更新:
我修改了代碼,以便localtime在每次迭代時都進行一次呼叫,以完全確保呼叫之間的分鐘數不會改變。
更緊湊但效率更低:
import time
while True:
minute= time.localtime().tm_min
if 'target' not in locals() or minute == target:
print("checking condition")
target= (minute 3) % 60
time.sleep(1)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/452713.html
下一篇:兩個日期時間之間的15分鐘間隔數
