Search code examples
python-3.xdatetimetimepauseuntil-loop

Python Wait /Pause until specific Time... And stop at end of schedule


With the following code, I am trying to run program between 9:15am and 17:30pm;; and it should esentially stop at 17:30pm and then, again wait until next day 9:15am without ending itself.

### For experiment sake, I have made the datetime.time(20,26) and (20,28)... 
### You may change it to any of the hours and mins of your time...
### But I am hoping it would start and stop between those times please... 

import time, datetime, pause

def printing_something():
    print("Hello World")  # you can add any func here

day_of_week = datetime.date.today().weekday() # (0=Monday), (5=Saturday) and (6=Sunday)
timer_now = datetime.datetime.now().time()

while True:
    if day_of_week < 5 and (timer_now > datetime.time(20,26) and timer_now < datetime.time(20,28)):
        time.sleep(5 - time.time() % 5)
        printing_something()
    else:
        pause.until(datetime(9, 15, 0))

Firstly... The problem with this code is it doesn't do anything at the start of the time, in case I start like an hour before the schedule... It shows it is running, but when the exact time comes(for example 20:26hours, like in code above), it just doesn't print anything that it is asked.

Secondly... If I happen to start inside the scheduled time, then it will start printing, but then it doesn't stop the printing at the end of 20:28hours, like it is scheduled to stop...

So, the question again... If I start the program anytime in day or night, and leave it... How to make it execute at 9:15am and make it stop at 17:30pm... and then allow the program to keep running(but paused) until the next day 9:15am....

(For more clarity, I was trying to run in the market hours only, between Monday to Friday... and parts of the code may not be relevant, but I am a rookie in python, sorry)


Solution

  • As there has not been much help from here, I have worked out a temporary work-around with the below code. I manually start the program execution at the start of the day, and then at 17:30pm, I close the program.

    import schedule
    import time
    
    def job():
        print("I'm working...")
    
    schedule.every(5).minutes.do(job)
    schedule.every().day.at("9:15").do(job)
    
    while True:
        schedule.run_pending()
        time.sleep(1)