我有一個執行兩種方法的while循環。我希望 functionB() 每 2 秒執行一次。我知道有一些解決方案可以使用線程使用計時器每兩秒執行一次,但這是我不想使用的東西。我希望這兩種方法都在 MAIN 線程上運行。def functionA(): # Code goes heredef functionB(): # Code goes herewhile True: # Execute function A functionA() # Periodically execute functionB every 2 seconds functionB()我不確定如何計算上次執行時間與當前時間之間的差異。我在網上搜索了一些例子,但它們似乎讓我更加困惑。任何幫助,將不勝感激。
1 回答

喵喵時光機
TA貢獻1846條經驗 獲得超7個贊
以秒為單位獲取時間戳,并檢查自上次執行以來是否經過了 2 秒或更多秒。
import time
def functionA():
# Code goes here
def functionB():
# Code goes here
lastExec = 0
while True:
# Execute function A
functionA()
now = time.time()
if now - lastExec >= 2:
# Periodically execute functionB every 2 seconds
functionB()
lastExec = now
添加回答
舉報
0/150
提交
取消