Python Crontab API

3.3.0 · active · verified Thu Apr 09

python-crontab provides a Pythonic API to create, manage, read, and write crontab entries and entire crontab files, including user-specific and system-wide crontabs. As of version 3.3.0, it offers a unified `CronTab` class for all crontab manipulations, simplifying interaction with cron jobs from Python. The library is actively maintained with an irregular release cadence.

Warnings

Install

Imports

Quickstart

This example initializes a crontab for the current user, adds a new job to run every minute, and then persists the changes to the user's crontab file. Remember that `write()` is crucial to save modifications. This requires the Python script to have appropriate permissions to modify the crontab.

from crontab import CronTab

# Initialize crontab for the current user. Permissions might be needed.
# For system-wide crontabs, use CronTab(user='root') and ensure proper permissions.
my_cron = CronTab(user=True)

# Create a new cron job
job = my_cron.new(command='echo "Hello from cron!" >> /tmp/cron_test.log', comment='my_test_job')
job.minute().every(1) # Run every minute

# Iterate existing jobs (optional)
print('Existing jobs:')
for j in my_cron:
    print(j)

# IMPORTANT: Write changes to the crontab file
my_cron.write()
print('Crontab updated. Check /tmp/cron_test.log in a minute.')

# To remove a job later (example):
# for job_to_remove in my_cron.find_comment('my_test_job'):
#     my_cron.remove(job_to_remove)
# my_cron.write()

view raw JSON →