I have a Python 3 script (using PRAW library) that executes once and ends. It currently is automated using cron jobs and runs every 45 minutes.
There is a need to change this to a persistence bot so the bot is always "online", so cron cannot be used. Part of this is easy enough:
def bot_loop():
running = True
while running:
try:
#This should occur constantly and monitor Reddit API stream
for submission in subreddit.stream.submissions(skip_existing=False):
print(submission.title)
#TODO: below condition to only execute the below every 45 minutes
health_checks()
except KeyboardInterrupt:
print('Keyboard Interrupt. Ending bot.')
running = False
except Exception as e:
print('Exception raised per below. Attempting to continue bot in 10 seconds.')
print(e)
time.sleep(10)
What would be the best logic in this loop to ensure the health checks only runs every 45 minutes? Meanwhile the rest of the script would continue and process. Additionally, what is the best way to also ensure that if for some reason it does not run on the 45th minute (say at xx:45:00
) such as perhaps CPU is busy elsewhere, it runs at the next opportunity?
The logic should be:
- The bot should be monitoring subreddit.stream.submissions() 24/7.
- Every 45 minutes, the bot should perform things like health checks.
Considerations could be if minute == 45, but that alone has issues (it would run at least 60 times in the minute).