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 :
JavaScript
x
17
17
1
import datetime
2
import time
3
4
delta_hour = 0
5
6
while:
7
now_hour = datetime.datetime.now().hour
8
9
if delta_hour != now_hour:
10
# run your code
11
12
delta_hour = now_hour
13
14
time.sleep(1800) # 1800 seconds sleep
15
16
# add some way to exit the infinite loop
17
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 :
JavaScript
1
8
1
start_time = int(time())
2
#main thread code
3
#main thread code end
4
if int(time() - start_time >= 60 * 60):
5
print("pausing time")
6
sleep(30 * 60)
7
start_time = int(time())
8
From the moment the script starts this will pause every hour for 30mins and resume afterwards .
Simple yet effective !