3

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!

eug1712
  • 33
  • 1
  • 3
  • Why not use a scheduler like cron? Though you'd still need to have it stop itself at 9pm. Unless you also put a command to stop it into the scheduler. – Cyphase Aug 15 '15 at 21:03
  • 1
    `time.sleep()` doesn't guarantee that it waits for the full time specified. It can return earlier or later, so you should at least use a while loop to wait the remaining time to the next wake up time. – Sven Marnach Aug 15 '15 at 21:05
  • Python's crontab https://pypi.python.org/pypi/python-crontab may be what you are looking for. – Pie 'Oh' Pah Aug 15 '15 at 21:20

3 Answers3

7

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
yask
  • 2,552
  • 2
  • 16
  • 27
  • Running on Windows, but the second section helps. – eug1712 Aug 15 '15 at 22:12
  • @eug1712 Try to look for `cron` alternatives for windows. Eg:The Windows "AT" command is very similar to cron. It is available through the command line. : http://stackoverflow.com/questions/132971/what-is-the-windows-version-of-cron – yask Aug 15 '15 at 22:40
1

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)).

Cyphase
  • 10,336
  • 2
  • 24
  • 31
-1

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
kezzos
  • 2,463
  • 2
  • 17
  • 30
  • 3
    This doesn't address the question. And if you're going to do this sort of thing, you should use a scheduler. – Cyphase Aug 15 '15 at 21:07