簡體   English   中英

Python:每n秒運行一次代碼並在條件下重啟計時器

[英]Python: Run code every n seconds and restart timer on condition

這可能比我想象的要簡單,但我想創建一個計時器,當達到一個限制(比如15分鍾)時,會執行一些代碼。

與此同時,我想測試一下情況。 如果滿足條件,則重置計時器並再次開始處理,否則倒計時繼續。

如果在倒計時結束后滿足條件,則執行一些代碼並且計時器再次開始倒計時。

這是否涉及threading或是否可以通過簡單的time.sleep()函數實現?

如果整個過程就像你說的一樣簡單,我會像這樣(半偽代碼):

def run_every_fifteen_minutes():
  pass
def should_reset_timer():
  pass
def main():
  timer = 0
  while True:
    time.sleep(1)
    timer+=1
    if should_reset_timer():
      timer = 0
    if timer == 15*60:
      run_every_fifteen_minutes()
      timer = 0

請注意,這不會是十五分鍾。它可能會延遲幾秒鍾。 睡眠不保證只能睡1秒,其余的循環也需要一些時間。 如果你需要它真正准確的話,你可以在那里添加一個系統時間比較。

您可以通過線程優雅地實現它,但如果您需要快速修復,您可以嘗試

import time
timer = 15 * 60 # 60 seconds times 15 mins
while timer > 0:
    time.sleep(0.985) # don't sleep for a full second or else you'll be off
    timer -= 1
    if someCondition:
          timer = 15 * 60
executeCode() # called when time is zero and while loop is exited

感謝大家的幫助,您的回答指出了我正確的方向。 最后我提出了:

#!/usr/bin/python
import RPi.GPIO as GPIO
import time
import subprocess

GPIO.setmode(GPIO.BCM)
PIR_PIN = 4
GPIO.setup(PIR_PIN, GPIO.IN)
timer = 15 * 60 # 60 seconds times 15 mins

subprocess.call("sudo /opt/vc/bin/tvservice -o", shell=True)

try :
    print "Screen Timer (CTRL+C to exit)"
    time.sleep(5)
    print "Ready..."

    while True:
        time.sleep(0.985)

        # Test PIR_PIN condition
        current_state = GPIO.input(PIR_PIN)

        if timer > 0:
            timer -= 1

            if current_state: #is true
                # Reset timer
                timer = 15 * 60

        else:
            if current_state: #is true
                subprocess.call("sudo /opt/vc/bin/tvservice -p", shell=True)

                # Reset timer
                timer = 15 * 60
            else:
                subprocess.call("sudo /opt/vc/bin/tvservice -o", shell=True)

except KeyboardInterrupt:
    print "Quit"
    GPIO.cleanup()

為了說明問題,我正在使用PIR傳感器檢測運動並在Raspberry Pi上打開hdmi連接的監視器。 在沒有移動15分鍾后,我想關閉顯示器,然后如果(稍后)檢測到移動,再次將其重新打開並重新開始計時。

描述聽起來類似於死主的開關 / 看門狗定時器 它的實現方式取決於您的應用程序:是否存在事件循環,是否存在阻塞函數,是否需要單獨的進程以進行正確的隔離等。如果代碼中沒有阻塞函數:

#!/usr/bin/env python3
import time
from time import time as timer

timeout = 900 # 15 minutes in seconds
countdown = timeout # reset the count
while True:
    time.sleep(1 - timer() % 1) # lock with the timer, to avoid drift
    countdown -= 1
    if should_reset_count():
        countdown = timeout # reset the count
    if countdown <= 0: # timeout happened
        countdown = timeout # reset the count
        "some code is executed"

該代碼假定睡眠永遠不會中斷(注意:在Python 3.5之前,睡眠可能會被信號中斷)。 該代碼還假設沒有任何功能需要很長時間(大約一秒鍾)。 否則,您應該使用明確的截止日期(相同的代碼結構):

deadline = timer() + timeout # reset
while True:
    time.sleep(1 - timer() % 1) # lock with the timer, to avoid drift
    if should_reset_count():
        deadline = timer() + timeout # reset
    if deadline < timer(): # timeout
        deadline = timer() + timeout # reset
        "some code is executed"

也許您應該查看Linux工具cron來安排腳本的執行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM