Home > OS >  How to start/stop a function at specific time of the day?
How to start/stop a function at specific time of the day?

Time:11-17

If I have a function that loops throughout the day denoted by:

def Show()

How can I run it so that at a particular time of the day it won't return anything?

In this instance say 13:50 to 14:20?

CodePudding user response:

If I understand the question correctly, you could just check the time using an if statement:

# import datetime module
from datetime import datetime as dt

# set to time bounds:
lower_bound = dt.time(13, 50)
upper_bound = dt.time(14, 20)

Then just check the time whenever the function runs:

now = dt.now().time()
if lower_bound < now < upper_bound:
     pass
if not (lower_boun < now < upper_bond):
     Show() #that returns something. 

(or just put the if statements into the function itself

Check out this question on now and this question on comparing time

Answer improved by helpful comments of chepner and 0x5423

CodePudding user response:

schedule is an excellent module for doing all of this. It even runs async without too much work.

https://schedule.readthedocs.io/en/stable/

schedule.every(1).hours.at("06:00").do(show).tag('show', 'guest')

and then stop the schedule at a specific time

schedule.every().day.at("10:30").clear('show')
  • Related