Search code examples
pythonpython-3.xpython-multithreadingschedulingexit

How to pause or stop python program between certain hours (not based on elapsed time!)


I am trying to find a way of leaving my python program running continuously, but ensuring that the main script is only 'active' during nightime hours (e.g. between 21:30 and 04:30 for example)

Background: My program records motion activated video & activates a floodlight.

The main program segment is below:

...I am currently running this each evening and then killing in the morning with Ctrl-C..!

try:

signal.signal(signal.SIGHUP,SigHandler) # proper exit for SIGHUP (terminal hangups)

while GPIO.input(PIR_PIN)==1: # Loop until PIR output is stabilised at 0
    pass

GPIO.add_event_detect(PIR_PIN, GPIO.RISING, callback=MotionDetected)

signal.pause() #pauses main program forever & waits for PIR Rising Edge unless interrupted

except KeyboardInterrupt:
    print("")

finally:
    GPIO.output(16, GPIO.LOW) #floodlight off
    GPIO.cleanup()

Is there a way of checking time periodically in a parallel thread perhaps, and suspending program if time betweeen certain hours?

Might the solution posted below work for my program perhaps if I add the thread statement before my try statement?...

How to schedule python script to exit at given time


Solution

  • First, create a cron job (I believe you're on Linux because of the GPIO calls), to start the script every night at 21:30.

    30 21 * * * python /path/to/python/script

    Then, create a second cron job at 4:30 to kill any existing processes that are running your program.

    30 4 * * * pkill -f /path/to/python/script # Will need to be edited to the actual process name that runs.

    Killing a process by matching name