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

Viewed 5733
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

3 Answers

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.

If you only want it to run once, add the line return schedule.CancelJob to the end of the function:

import schedule
import time
def test():
    print("Stopped")
    return schedule.CancelJob
schedule.every().day.at("21:43").do(test)
while True:
    schedule.run_pending()
    time.sleep(1)

If you want to break the loop:

import schedule
import time
running = True
def test():
    global running
    running = False
    print("Stopped")
    return schedule.CancelJob
schedule.every().day.at("21:43").do(test)
while running:
    schedule.run_pending()
    time.sleep(1)

Here are the relevant docs

The python schedule library seems to be for periodic jobs. What you are describing is more of a time triggered job. You'd better check time in your while True loop.

By the way, if you tag your job, you can use the schedule.cancel_job(tag) to cancel your job.

Related