Search code examples
pythonschedule

How to cancel scheduled job once it's completed -Python


import schedule
import time
def test():
    print("Stopped")
    # I tried these two commands below it's not helping or maybe I am doing it wrong.
    # schedule.cancel_job(test)
    # schedule.clear()
schedule.every().day.at("21:43").do(test)
while True:
    schedule.run_pending()
    time.sleep(1)

I want to cancel job once it's completed, here I know it's not completed because I have used day so it runs each day, but I just want to cancel this job once it's performed or if is there any other way to do same thing it will be good and it must be easy like schedule. Technically I have created a python bot there are multiple scheduled tasks I want to implement this idea there. Plus I am not understanding this if it relates to my query:

how to cancel python schedule


Solution

  • It sounds like you only want the scheduled task to run once.

    If so, this is an FAQ on the schedule webpage and it gives the following suggestion

    def job_that_executes_once():
        # Do some work ...
        return schedule.CancelJob
    
    schedule.every().day.at('22:30').do(job_that_executes_once)
    

    See https://schedule.readthedocs.io/en/stable/faq.html#how-can-i-run-a-job-only-once

    A better way to exit the program once all the jobs have completed or been cancelled is as follows

    import schedule
    import time
    
    def test():
        print("Running")
        return schedule.CancelJob
    
    schedule.every().minute.do(test)
    while True:
        schedule.run_pending()
        if not schedule.jobs:
            break
        time.sleep(1)
    
    print("I'm done")
    

    This code will break out of the while loop when there are no more jobs in schedules list.