How to Schedule Python Jobs at Specific Times and Cancel Them
Learn how to schedule Python jobs at specific times and cancel them reliably with the schedule library and APScheduler.

Why Scheduling at a Specific Time Requires a Cancellation Strategy
When you need to run a function at a precise moment—say, a data export at 02:00 UTC or a cleanup task every Monday at 09:30—you typically reach for a scheduling library. The common workflow is straightforward at first: define the job, set the time, and let the scheduler loop run. The complication appears when the job must be canceled before it fires, either because the condition changed, the process is shutting down, or the job itself needs to be removed from the queue.
The Python ecosystem offers several ways to schedule a job at a specific time. The most popular are the schedule library, which has a simple, human-readable API, and APScheduler, which offers more advanced triggers, persistence, and job stores. Both support cancellation, but the mechanism differs. This article walks through both approaches, shows how to cancel jobs cleanly, and explains the threading and lifecycle implications to keep in mind.
Scheduling with the schedule Library
The schedule library is a lightweight, dependency-free option for basic time-based scheduling. It lets you write code like this:
import schedule
import time
def task():
print('Running scheduled job')
# Schedule the task to run at 14:30 every day
schedule.every().day.at('14:30').do(task)
while True:
schedule.run_pending()
time.sleep(1)The at() method accepts a 24-hour time string. The loop repeatedly checks whether any scheduled jobs are due and runs them. This is a blocking loop, so you typically run it in the main thread or in a dedicated thread.
Canceling a job in schedule requires keeping a reference to the job object returned by .do():
def task():
print('Running scheduled job')
job = schedule.every().day.at('14:30').do(task)
# Later, when you want to cancel it
schedule.cancel_job(job)The cancel_job function removes the job from the scheduler's internal job list. After cancellation, the job will not run again, even if the scheduled time passes. If you need to cancel from inside the job itself, you can hold the job reference in a mutable container or global variable, but a cleaner approach is to keep the job reference where the cancellation decision is made and cancel from there.
One limitation of schedule is that it does not support timezone-aware scheduling out of the box. The at() time is interpreted in the local timezone of the process. If your deployment spans multiple timezones, convert the target time to the server's local time before calling at(). This is a common source of errors when scheduling jobs that must run at a specific UTC time.
Scheduling with APScheduler
APScheduler is a more powerful library that supports multiple triggers, job stores, and executors. For a one-off job at a specific time, the date trigger is the natural fit:
from apscheduler.schedulers.background import BackgroundScheduler
from datetime import datetime, timedelta
def task():
print('One-off job executed')
scheduler = BackgroundScheduler()
run_time = datetime.now() + timedelta(minutes=5)
scheduler.add_job(task, 'date', run_date=run_time, id='my_job')
scheduler.start()add_job returns a Job object; the actual job ID is either the id you supply or a generated value. To cancel the job before it runs, call remove_job with that ID:
scheduler.remove_job('my_job')If you do not know the ID, you can retrieve it from the job object returned by add_job:
job = scheduler.add_job(task, 'date', run_date=run_time)
job_id = job.id
# Later
scheduler.remove_job(job_id)APScheduler also supports reschedule_job when you need to change the run time instead of canceling. This is useful when a job should be postponed rather than removed entirely.
A key difference from schedule is that APScheduler runs jobs in a pool of worker threads by default. The scheduler itself runs in a background thread, so your main program can continue doing other work. That makes it easier to integrate into a larger application, but it also means you need to think about thread safety if your job modifies shared state.
Canceling a Job from Within the Job Itself
There are cases where a job should stop itself based on a condition discovered at runtime—for example, a job that polls an external service and stops when a certain response is received. In schedule, you can hold the job reference in a mutable container:
import schedule
import time
job_holder = {}
def task():
if should_stop():
schedule.cancel_job(job_holder['job'])
else:
print('Still running')
job_holder['job'] = schedule.every().day.at('14:30').do(task)
while True:
schedule.run_pending()
time.sleep(1)In APScheduler, you can remove the job from inside the job function by referring to the scheduler instance. Use the job ID you assigned when adding the job:
from apscheduler.schedulers.background import BackgroundScheduler
from datetime import datetime, timedelta
scheduler = BackgroundScheduler()
run_time = datetime.now() + timedelta(minutes=5)
def task():
if should_stop():
scheduler.remove_job('my_job')
else:
print('Still running')
scheduler.add_job(task, 'date', run_date=run_time, id='my_job')
scheduler.start()Self-cancellation is most relevant for interval or cron triggers that repeat. A one-off date trigger disappears after it runs, so if you need to prevent that single run, cancel it before the scheduled time, usually from outside the job.
Threading and the Scheduler Loop
Both libraries can run their scheduling loop in a background thread. The schedule library does not provide a built-in background thread; you must create one yourself if you do not want to block the main thread:
import threading
import schedule
import time
def run_scheduler():
while True:
schedule.run_pending()
time.sleep(1)
thread = threading.Thread(target=run_scheduler, daemon=True)
thread.start()
# Main program continuesThe daemon=True flag means the thread will not prevent the process from exiting when the main thread finishes. This is convenient for short scripts, but be careful if you must perform cleanup before exit: if the scheduler thread is stopped abruptly, pending jobs may not run, and resources they hold may not be released.
APScheduler's BackgroundScheduler already runs in a background thread and provides a shutdown() method that gracefully stops the scheduler and waits for running jobs to finish. Call shutdown() in a finally block or a signal handler to ensure a clean exit.
scheduler = BackgroundScheduler()
# ... add jobs
scheduler.start()
try:
# main program
while True:
time.sleep(1)
except KeyboardInterrupt:
scheduler.shutdown()If you use a persistent job store and the process exits without shutdown(), the job store may be left in an inconsistent state.
Error Handling and Edge Cases
Scheduled jobs can fail for many reasons: the function raises an exception, the system clock changes, or the scheduled time is already in the past. The two libraries handle these situations differently.
With schedule, if a job raises an exception, the exception propagates to the run_pending() call. If you do not catch it, the loop stops. To keep the scheduler alive, wrap the job execution in a try-except inside the job function, or catch exceptions around run_pending():
while True:
try:
schedule.run_pending()
except Exception as e:
print(f'Scheduler error: {e}')
time.sleep(1)APScheduler does not let a job exception bring down the scheduler; it reports the failure through its logging configuration and leaves the job scheduled. If you want a job to be removed after a failure, handle that explicitly.
Another edge case is scheduling a job for a time that has already passed. With schedule, a daily at() job normally runs at the next occurrence—for example, at the same time tomorrow if the time has passed today. APScheduler's date trigger behavior for a past run_date depends on the scheduler's misfire_grace_time setting and the library version. In production code, check the behavior in your version or set the misfire policy explicitly so the result is not a surprise.
Timezones are a subtler issue. schedule uses the local timezone, while APScheduler can be configured with a timezone through the scheduler constructor or trigger. For systems that run across timezones or through DST changes, specify an explicit timezone.
Choosing the Right Scheduling Approach
The choice between schedule, APScheduler, and a simple threading.Timer depends on the complexity of your scheduling needs.
| Feature | schedule | APScheduler | threading.Timer |
|---|---|---|---|
| API simplicity | Very simple | More complex | Minimal |
| One-off specific time | No native one-off; at() repeats daily until canceled or cleared | Yes (date trigger) | Yes (delay in seconds) |
| Cancellation | cancel_job(job) | remove_job(job_id) | timer.cancel() |
| Timezone support | Local only | Configurable | Local only |
| Background thread | Not built-in | Built-in | Not built-in |
| Persistent job store | No | Yes (SQLite, Redis, etc.) | No |
| Cron-like schedules | Yes (via every().day) | Yes (cron trigger) | No |
Use schedule when you need a quick, readable script with minimal dependencies and do not require timezone-aware scheduling. Use APScheduler when your application needs more robust scheduling, job persistence, or multiple trigger types. Use threading.Timer for a one-off delayed call that you can cancel with timer.cancel(), but note that it accepts only a delay in seconds, not an absolute time—you must calculate the delay yourself.
For a job that must run at a specific absolute time and be cancellable, APScheduler's date trigger is the most reliable choice because it handles the time calculation and exposes a clear cancellation API. threading.Timer is acceptable for simple cases, but it cannot reschedule or persist jobs.
Production Considerations for Long-Running Schedulers
When a scheduler runs inside a web application or a long-lived service, think about how it interacts with the application lifecycle. A common mistake is to start a scheduler at module import time, which can create duplicate schedulers when the module is imported more than once. Create the scheduler in an application factory or a dedicated service class instead.
Job stores matter too. APScheduler's default memory store loses all jobs when the process restarts. If jobs must survive a restart, configure a persistent job store such as SQLite or Redis. That also allows multiple processes to share the same job schedule, but then you must handle locking and job-store concurrency.
Finally, monitor scheduler health. A job that blocks for too long can occupy a worker thread; if all workers in the pool are occupied, later jobs may be delayed. Set timeouts on network calls inside jobs, and configure the thread pool executor with a sensible maximum number of workers for your workload.
Try matching browser tools
All toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesPython iter(): How the Built-in Function Works
Explains Python's iter() built-in: how it creates iterators, the two-argument sentinel form, custom iterator classes, and common edge cases.
Python Pika: Queues, Exchanges, Routing Keys, and Acknowledgements
Learn how to use Python's Pika client with RabbitMQ: declare queues and exchanges, publish with routing keys, consume messages, and handle acknowledgements reliably.
Python Kafka: kafka-python vs Confluent Client
python kafka python vs confluent kafka: Compare kafka-python and Confluent Kafka Python clients: API differences, performance, feature coverage, and when to choose eac...
Python Kafka Offsets, Partitions, and Manual Commits
Learn how Kafka offsets and partitions work and how to manually commit offsets in Python consumers with kafka-python and confluent-kafka. Covers sync vs async commits, rebalances, and seeking.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.