Reputation: 1
Currently, I have this script which if it errors, it completely restarts. Which is perfect for what I need.
But there is one problem, I want the script to automatically restart, even when it did not crash. every 30 seconds.
This is what I have:
while True:
try:
do_main_logic()
except:
pass
I am expecting for it to just restart the entire script every 30 seconds and start from the begin. Even if it has not crashed or not.
Upvotes: 0
Views: 91
Reputation: 106
I think you just have to add time.sleep(30)
import time
while True:
time.sleep(30)
try:
do_main_logic()
except:
pass
Upvotes: 0
Reputation: 29
I think what you need is threading.Timer
. To use Timer
, You can modify your do_main_logic()
in the following way:
from threading import Timer
def do_main_logic():
running = True
def Timeout():
nonlocal running
running = False
Timer(30, Timeout).start()
while running: # and your loop conditions
# your code here
You need to find a suitable place to constantly check the variable running
.
Upvotes: 0
Reputation: 1845
If you want to restart each 30 second, maybe you can do a sort of:
import time
while True:
try:
do_main_logic()
except:
pass
finally:
time.sleep(30)
In this way at the end of the while, in both cases you hit the try
or the except
the script will sleep for 30 second.
Upvotes: 1