ZetCode

Python schedule

last modified November 29, 2026 Python 3.15

In this article we show how to run periodic jobs with the schedule library.

schedule is a small library for running Python functions at regular intervals or at specific times, with a readable syntax such as every(10).minutes.do(job). It runs inside our program: there is no daemon and no persistence, and the jobs run only while the program keeps calling the scheduler. For jobs that must survive restarts, a system scheduler such as cron or systemd timers is a better fit. The standard library has a lower-level sched module. The examples use schedule 1.2.

$ pip install schedule

The first job

A job is created with every, a time unit, and do, which takes the function to run. The program must then call run_pending regularly.

first_job.py
import time

import schedule

start = time.monotonic()


def job():
    print(f'{time.monotonic() - start:.0f}s: Hello there!')


schedule.every(2).seconds.do(job)

for _ in range(7):
    schedule.run_pending()
    time.sleep(1)

The job runs every two seconds. The run_pending function runs all jobs that are due; it does not wait. The loop calls it once a second for seven seconds, so the job runs three times. Real programs usually loop forever with while True. The job prints the time elapsed since the start, measured with time.monotonic.

$ python first_job.py
2s: Hello there!
4s: Hello there!
6s: Hello there!

Several jobs with arguments

Extra arguments of do are passed to the job function. Each call of every creates a new job with its own interval.

several_jobs.py
import time

import schedule

start = time.monotonic()


def greet(name, greeting='Hello'):
    print(f'{time.monotonic() - start:.0f}s: {greeting} there, {name}!')


schedule.every(2).seconds.do(greet, 'Peter')
schedule.every(3).seconds.do(greet, 'Lucia', greeting='Hi')

while time.monotonic() - start < 6.5:
    schedule.run_pending()
    time.sleep(max(0, schedule.idle_seconds()))

The same function runs as two jobs with different arguments and intervals. Instead of a fixed pause, the loop sleeps for idle_seconds, the number of seconds until the next job is due. The value can be slightly negative when a job is already late, hence the max.

$ python several_jobs.py
2s: Hello there, Peter!
3s: Hi there, Lucia!
4s: Hello there, Peter!
6s: Hi there, Lucia!
6s: Hello there, Peter!

Intervals and times

Besides seconds, the units are minutes, hours, days, and weeks. The at method sets the time of day for daily jobs, the minute for hourly jobs, and a weekday can be used instead of a unit.

intervals.py
import schedule


def report():
    pass


schedule.every(10).minutes.do(report)
schedule.every().hour.at(':15').do(report)
schedule.every().day.at('06:30').do(report)
schedule.every().monday.at('08:00:30').do(report)
schedule.every(2).weeks.do(report)
schedule.every(5).to(10).minutes.do(report)

for job in schedule.get_jobs():
    print(repr(job))

print(f'next run: {schedule.next_run():%Y-%m-%d %H:%M:%S}')

The every().hour.at(':15') job runs at a quarter past each hour and every().monday.at('08:00:30') once a week. The to method makes the interval random: the last job runs after five to ten minutes, picked anew after each run. The repr of a job describes it with the times of its last and next run, and next_run returns the time of the earliest job. The output depends on when the program runs; this run was on Sunday afternoon. The at method also accepts a time zone name as the second argument, which requires the pytz package.

$ python intervals.py
Every 10 minutes do report() (last run: [never], next run: 2026-11-29 15:03:29)
Every 1 hour at 00:15:00 do report() (last run: [never], next run: 2026-11-29 15:15:00)
Every 1 day at 06:30:00 do report() (last run: [never], next run: 2026-11-30 06:30:00)
Every 1 week at 08:00:30 do report() (last run: [never], next run: 2026-11-30 08:00:30)
Every 2 weeks do report() (last run: [never], next run: 2026-12-13 14:53:29)
Every 5 to 10 minutes do report() (last run: [never], next run: 2026-11-29 15:02:29)
next run: 2026-11-29 15:02:29

Cancelling jobs

A job that returns schedule.CancelJob is removed after it runs. The cancel_job function removes a job from outside.

run_once.py
import time

import schedule

start = time.monotonic()


def remind():
    print(f'{time.monotonic() - start:.0f}s: drink some water')
    return schedule.CancelJob


def tick():
    print(f'{time.monotonic() - start:.0f}s: tick')


schedule.every(2).seconds.do(remind)
ticker = schedule.every(1).seconds.do(tick)

while schedule.get_jobs():
    schedule.run_pending()

    if time.monotonic() - start > 3.5:
        schedule.cancel_job(ticker)

    time.sleep(1)

print('no jobs left')

The reminder runs once: it returns CancelJob after the first run. The do method returns the job, so we can keep a reference to the ticker and cancel it after about three and a half seconds. The loop ends when get_jobs returns an empty list.

$ python run_once.py
1s: tick
2s: drink some water
2s: tick
3s: tick
4s: tick
no jobs left

Running until a deadline

The until method sets a time after which the job is no longer run. It accepts a datetime, a timedelta, a time, or a string.

until.py
import time
from datetime import timedelta

import schedule

start = time.monotonic()


def poll():
    print(f'{time.monotonic() - start:.0f}s: checking the queue')


schedule.every(1).seconds.until(timedelta(seconds=3.5)).do(poll)

while schedule.get_jobs():
    schedule.run_pending()
    time.sleep(1)

print(f'{time.monotonic() - start:.0f}s: polling stopped')

The job polls a queue every second for three and a half seconds. When the job is due after the deadline, the scheduler cancels it instead of running it, so the loop ends.

$ python until.py
1s: checking the queue
2s: checking the queue
3s: checking the queue
4s: polling stopped

Tags

Jobs can be tagged with one or more labels. Tags select jobs for get_jobs and clear.

tags.py
import schedule


def backup(target):
    print(f'backing up {target}')


def clean():
    print('cleaning temporary files')


schedule.every().day.at('01:00').do(backup, 'database').tag('backup', 'db')
schedule.every().day.at('02:00').do(backup, 'files').tag('backup')
schedule.every().hour.do(clean).tag('maintenance')

print(len(schedule.get_jobs('backup')))

schedule.run_all()

schedule.clear('db')
print(len(schedule.get_jobs('backup')), len(schedule.get_jobs()))

schedule.clear()
print(schedule.get_jobs())

Two jobs have the backup tag. The run_all function runs all jobs immediately, regardless of their schedule, which is useful for testing. Clearing the db tag removes the database backup, and clear without a tag removes all jobs.

$ python tags.py
2
backing up database
backing up files
cleaning temporary files
1 2
[]

The repeat decorator

The repeat decorator schedules a function where it is defined. Arguments after the job specification are passed to the function.

decorator.py
import time

from schedule import every, repeat, run_pending

start = time.monotonic()


@repeat(every(2).seconds)
def heartbeat():
    print(f'{time.monotonic() - start:.0f}s: alive')


@repeat(every(3).seconds, 'disk')
def check(resource):
    print(f'{time.monotonic() - start:.0f}s: {resource} ok')


for _ in range(7):
    run_pending()
    time.sleep(1)

The decorator registers the jobs with the default scheduler when the functions are defined, so the loop only calls run_pending. Both jobs are due at six seconds; the scheduler runs due jobs in the order of their exact due times, and the disk check became due a fraction of a second earlier. The Python decorators article explains decorators.

$ python decorator.py
2s: alive
3s: disk ok
4s: alive
6s: disk ok
6s: alive

Handling errors

The scheduler does not catch exceptions. An exception raised in a job propagates out of run_pending and, unless we catch it, ends the program and all other jobs with it.

errors.py
import functools
import itertools
import time

import schedule

start = time.monotonic()
attempts = itertools.count(1)


def catch_errors(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except Exception as e:
            print(f'{func.__name__} failed: {e!r}')
    return wrapper


@catch_errors
def fetch():
    attempt = next(attempts)
    if attempt == 2:
        raise ConnectionError('server not responding')
    print(f'{time.monotonic() - start:.0f}s: fetch #{attempt} done')


schedule.every(1).seconds.do(fetch)

for _ in range(4):
    schedule.run_pending()
    time.sleep(1)

The catch_errors decorator wraps the job, prints the exception, and returns normally, so the job stays scheduled. The second attempt fails, the third one runs as usual. In a real program, the error would be logged with the logging module.

$ python errors.py
1s: fetch #1 done
fetch failed: ConnectionError('server not responding')
3s: fetch #3 done

Running in the background

The run_pending loop blocks the program. To do other work at the same time, we can run the loop in a background thread. A separate Scheduler object keeps its jobs apart from the default scheduler.

background.py
import threading
import time

import schedule

start = time.monotonic()


def run_continuously(scheduler, interval=1):
    stop = threading.Event()

    def loop():
        while not stop.wait(interval):
            scheduler.run_pending()

    threading.Thread(target=loop, daemon=True).start()
    return stop


def job():
    print(f'{time.monotonic() - start:.1f}s: background job')


scheduler = schedule.Scheduler()
scheduler.every(2).seconds.do(job)

stop = run_continuously(scheduler)

for i in range(3):
    print(f'{time.monotonic() - start:.1f}s: main thread working')
    time.sleep(2.5)

stop.set()
print('scheduler stopped')

The run_continuously function starts a daemon thread that calls run_pending once a second and returns an Event that stops it. The wait method of the event sleeps for the interval but returns True as soon as the event is set. Meanwhile, the main thread does its own work. The jobs run in the background thread, so the data they share with the main thread must be protected, for example with a lock.

$ python background.py
0.0s: main thread working
2.0s: background job
2.5s: main thread working
4.0s: background job
5.0s: main thread working
6.0s: background job
scheduler stopped

Source

schedule documentation

In this article we have run periodic jobs with the schedule library: intervals and times, job arguments, cancelling, deadlines, tags, the repeat decorator, error handling, and a background scheduler thread. See also Python sched, Python time module, and Python ThreadPoolExecutor.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.