Search code examples
pythonpython-2.7timing

How to run Python script only during certain hours of the day?


I've got a script that I need to run between 7am and 9pm. The script already runs indefinitely but if I am able to maybe pause it outside the above hours then that'd minimize the amount of data it would produce.

I currently use time.sleep(x) in some sections but time.sleep(36000) seems a bit silly?

Using Python 2.7

Thanks in advance!


Solution

  • You should use cron jobs (if you are running Linux).

    Eg: To execute your python script everyday between 7 am and 9 am.

    0 7 * * * /bin/execute/this/script.py
    
    • minute: 0
    • of hour: 7
    • of day of month: * (every day of month)
    • of month: * (every month)
    • and week: * (All)

    Now say you want to exit the program at 9 am .

    You can implement your python code like this so that it gets terminated automatically after 2 hours.

    import time
    
    start = time.time()
    
    PERIOD_OF_TIME = 7200 # 120 min
    
    while True :
        ... do something
    
        if time.time() > start + PERIOD_OF_TIME : break