I am trying to make a python script that works in a loop mode with iteration through a text file to run for periods of one hour and make 30minute pauses between each hour loop .
After some searching I found this piece of code :
import datetime import time delta_hour = 0 while: now_hour = datetime.datetime.now().hour if delta_hour != now_hour: # run your code delta_hour = now_hour time.sleep(1800) # 1800 seconds sleep # add some way to exit the infinite loop
This code has a few issues though :
- It does not consider one hour periods since the script starts running
- It does not seem to work continuously for periods over one hour
Considering what I am trying to achieve (running script 1hour before each time it pauses for 30mins) what is the best approach to this ? Cron is not an option here .
For clarification :
1hour run — 30min pause — repeat
Thanks
Advertisement
Answer
The simplest solution I could come up with was the following piece of code, which I added inside my main thread :
start_time = int(time()) ... #main thread code #main thread code end if int(time() - start_time >= 60 * 60): print("pausing time") sleep(30 * 60) start_time = int(time())
From the moment the script starts this will pause every hour for 30mins and resume afterwards .
Simple yet effective !