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

Question:

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!

Asked By: eug1712

||

Answers:

You could use the time functions to check what time of day it is, then call your script when you need to:

import time
import subprocess

process = None
running = False

while True:
    if time.daylight and not running:
        # Run once during daylight
        print 'Running script'
        process = subprocess.Popen("Myscript.py")
        running = True
    elif not time.daylight and running:
        # Wait until next day before executing again
        print 'Terminating script'        
        process.kill()
        running = False
    time.sleep(600)  # Wait 10 mins
Answered By: kezzos

You should look into using a scheduler like cron. However, if the script is going to run indefinitely, I think time.sleep(36000) is acceptable (or time.sleep(10*60*60)).

Answered By: Cyphase

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
Answered By: yask
import time
from datetime import datetime

if 7 <= int(datetime.fromtimestamp(time.time()).strftime('%H')) < 9:
    print(int(datetime.fromtimestamp(time.time()).strftime('%H')))
Answered By: Gryu
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.