Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 706
eug1712 Avatar asked Aug 31 '25 01:08

eug1712


2 Answers

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
like image 77
yask Avatar answered Sep 02 '25 13:09

yask


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

like image 32
Cyphase Avatar answered Sep 02 '25 15:09

Cyphase