How to Create a Cron Job in Python: Simple Guide
To create a cron job in Python, write your Python script and schedule it using the system's
cron service by adding a cron expression in the crontab file. Alternatively, use Python libraries like schedule to run tasks at intervals within your script.Syntax
A cron job is scheduled using a cron expression in the crontab file. The syntax has five fields followed by the command:
minute(0-59)hour(0-23)day of month(1-31)month(1-12)day of week(0-6, Sunday=0 or 7)commandto run (e.g., Python script)
Example: 0 6 * * * /usr/bin/python3 /path/to/script.py runs the script every day at 6:00 AM.
bash
0 6 * * * /usr/bin/python3 /path/to/script.py
Example
This example shows how to schedule a Python script to print a message every minute using the schedule library inside Python.
python
import schedule import time def job(): print("Running scheduled job...") schedule.every(1).minute.do(job) while True: schedule.run_pending() time.sleep(1)
Output
Running scheduled job...
Running scheduled job...
Running scheduled job...
... (prints every minute)
Common Pitfalls
Common mistakes when creating cron jobs include:
- Using the wrong path to the Python interpreter or script.
- Not giving execute permission to the script.
- Environment variables missing in cron context (cron runs with limited environment).
- Forgetting to redirect output or errors, so debugging is hard.
Always use full paths and test your script manually before scheduling.
bash
Wrong cron entry (missing full path): 0 6 * * * python script.py Correct cron entry: 0 6 * * * /usr/bin/python3 /home/user/script.py >> /home/user/log.txt 2>&1
Quick Reference
| Field | Description | Example |
|---|---|---|
| Minute | Minute of the hour (0-59) | 0 |
| Hour | Hour of the day (0-23) | 6 |
| Day of Month | Day of the month (1-31) | * |
| Month | Month of the year (1-12) | * |
| Day of Week | Day of the week (0-6, Sunday=0 or 7) | * |
| Command | Command or script to run | /usr/bin/python3 /path/to/script.py |
Key Takeaways
Use the system crontab with correct cron syntax to schedule Python scripts.
Always specify full paths for Python and your script in cron jobs.
Test your Python script manually before scheduling it as a cron job.
Use Python libraries like schedule for simple in-script task scheduling.
Redirect output and errors in cron to log files for easier debugging.