Automate with confidence: Master cron syntax, environmental variables, output logging, and practical examples for your Ubuntu server.
Estimated Time: Approximately 45 - 75 minutes (initial setup, examples, and understanding)
A Cron Job is a time-based job scheduler in Unix-like operating systems (like Ubuntu). It allows you to automate repetitive tasks by scheduling scripts or commands to run at specific intervals. Think of it as your server's personal alarm clock, but for tasks instead of waking you up!
The `cron` daemon (a background service) continuously runs and checks for scheduled jobs in special files called `crontabs`. When the scheduled time arrives, `cron` executes the associated command or script.
Why Use Cron Jobs?
45 - 75 minutes
(For initial setup, understanding syntax, and running through practical examples.)
Novice
Basic familiarity with the Linux terminal and file system is helpful but not strictly required.
sudo
privileges.Always ensure your system is up-to-date before configuring new services or tools.
sudo apt update && sudo apt upgrade -y
Cron jobs are stored in `crontab` files. There are two main types:
To add or modify cron jobs for your user, you use the `crontab` command.
Open your crontab for editing:
crontab -e
Add your cron job entries to this file. Each entry follows a specific format (explained next). Save and exit the editor (`Ctrl+O`, `Enter`, then `Ctrl+X` for `nano`).
A cron job entry consists of five time fields, followed by the command or script to execute.
The format is: minute hour day_of_month month day_of_week command
Position | Field | Allowed Values | Description |
---|---|---|---|
1 | Minute | 0-59 |
The minute of the hour (e.g., `0` for the start of the hour). |
2 | Hour | 0-23 |
The hour of the day (e.g., `0` for midnight, `12` for noon, `17` for 5 PM). |
3 | Day of Month | 1-31 |
The day of the month (e.g., `1` for the first day). |
4 | Month | 1-12 |
The month of the year (e.g., `1` for January, `12` for December). |
5 | Day of Week | 0-7 |
The day of the week (0 or 7 for Sunday, 1 for Monday, `6` for Saturday). |
For convenience, you can use these instead of the five time fields:
As mentioned in the warnings, cron jobs run with a very minimal environment. This is often the cause of scripts failing when run via cron but working perfectly manually.
You can define environment variables at the top of your `crontab` file, before any job definitions.
Common variables to set:
How to get your current `PATH`:
echo $PATH
Example of setting variables in `crontab`:
SHELL=/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin
MAILTO=""
# Your cron jobs start here...
By default, cron emails any output from your commands to the user's local mail spool. To prevent this (and potential disk-filling), you should redirect output.
Here are common cron job scenarios. Remember to use absolute paths for everything!
First, create your Bash script (e.g., `/home/ubuntu/scripts/daily_backup.sh`):
#!/bin/bash
# Script to perform a daily backup
BACKUP_DIR="/home/ubuntu/backups"
DATE=$(date +"%Y%m%d_%H%M%S")
mkdir -p $BACKUP_DIR
echo "Starting daily backup at $DATE..." >> $BACKUP_DIR/backup.log
tar -czvf $BACKUP_DIR/my_project_$(date +"%Y%m%d").tar.gz /var/www/my_project/ >> $BACKUP_DIR/backup.log 2>&1
echo "Backup finished." >> $BACKUP_DIR/backup.log
# Optional: Clean up old backups (e.g., older than 7 days)
find $BACKUP_DIR -name "*.tar.gz" -type f -mtime +7 -delete
echo "Old backups cleaned." >> $BACKUP_DIR/backup.log
Make the script executable:
chmod +x /home/ubuntu/scripts/daily_backup.sh
Add to crontab (`crontab -e`): Run daily at 2:30 AM.
30 2 * * * /home/ubuntu/scripts/daily_backup.sh >> /var/log/my_backup_cron.log 2>&1
Create your PHP script (e.g., `/var/www/html/my_app/process_queue.php`):
#!/usr/bin/php
<?php
// Script to process a background queue
$logFile = '/var/log/my_php_cron.log';
file_put_contents($logFile, date('[Y-m-d H:i:s]') . " PHP queue processing started.\n", FILE_APPEND);
// Simulate some work
sleep(5);
// Add your PHP application logic here
// e.g., require_once __DIR__ . '/bootstrap.php';
// (new App\QueueProcessor())->process();
file_put_contents($logFile, date('[Y-m-d H:i:s]') . " PHP queue processing finished.\n", FILE_APPEND);
?>
Make the script executable:
chmod +x /var/www/html/my_app/process_queue.php
Add to crontab (`crontab -e`): Run every 10 minutes.
*/10 * * * * /usr/bin/php /var/www/html/my_app/process_queue.php >> /var/log/my_php_cron_errors.log 2>&1
Assume you have a compiled Java application in a JAR file (e.g., `/home/ubuntu/java_apps/my_java_processor.jar`).
Add to crontab (`crontab -e`): Run every hour at 15 minutes past the hour.
15 * * * * /usr/bin/java -jar /home/ubuntu/java_apps/my_java_processor.jar >> /var/log/my_java_cron.log 2>&1
This is useful for triggering webhooks, internal APIs, or "pinging" your application's internal cron scheduler.
Add to crontab (`crontab -e`): Fetch a URL every 5 minutes.
*/5 * * * * /usr/bin/curl -s "https://yourdomain.com/api/cron/job" > /dev/null 2>&1
Create your Python script (e.g., `/home/ubuntu/scripts/data_cleaner.py`):
#!/usr/bin/python3
import datetime
import sys
log_file = '/var/log/my_python_cron.log'
def log_message(message):
with open(log_file, 'a') as f:
f.write(f"[{datetime.datetime.now()}] {message}\n")
log_message("Python data cleaner started.")
# Simulate some data cleaning
# Example: delete old records from a database or clean temporary files
log_message("Simulating data cleaning for 10 seconds...")
import time
time.sleep(10)
log_message("Python data cleaner finished.")
sys.exit(0) # Exit successfully
Make the script executable:
chmod +x /home/ubuntu/scripts/data_cleaner.py
Add to crontab (`crontab -e`): Run daily at 1:00 AM.
0 1 * * * /usr/bin/python3 /home/ubuntu/scripts/data_cleaner.py >> /var/log/my_python_cron_errors.log 2>&1
Directly in `crontab -e`:
# Every minute
* * * * * /usr/bin/command_every_minute
# Every 15 minutes
*/15 * * * * /usr/bin/command_every_15_minutes
# Every hour (at minute 0)
0 * * * * /usr/bin/command_every_hour
# Daily at 3:00 AM
0 3 * * * /usr/bin/command_daily_at_3am
# Weekly on Monday at 00:00 (midnight)
0 0 * * 1 /usr/bin/command_weekly_monday
# Monthly on the 1st day at 04:00 AM
0 4 1 * * /usr/bin/command_monthly_first_day
# Run at 8:00 AM and 5:00 PM every weekday (Monday-Friday)
0 8,17 * * 1-5 /usr/bin/command_weekday_morning_evening
# Using special strings (example for a daily task)
@daily /usr/bin/command_at_midnight_daily
Manually constructing cron strings can be tricky. Use this helper to understand each field and build your command. For complex schedules, online cron expression generators are invaluable.
Fill in your desired values for each field. Use `*` for "every" and `N` for a specific number.
Generated Cron String (Copy & Paste):
Manage your crontab entries once they are set.
View your current cron jobs:
crontab -l
Delete all your cron jobs:
crontab -r
Confirm your cron jobs are correctly configured and working:
You've now mastered the fundamentals of Cron Jobs on Ubuntu, enabling you to automate a vast array of tasks on your server. This powerful tool significantly enhances efficiency and reliability for your applications and system maintenance.
Consider these advanced steps and best practices for robust cron job management:
Need Expert Automation or System Administration Support? Contact Us!