Skip to main content

Scheduling Tasks with Cron

1. Editing Crontab

Command Description Example
crontab -e Open the crontab file in the default editor crontab -e
crontab -l List the current crontab entries crontab -l
crontab -r Remove the current crontab crontab -r
crontab filename Install a new crontab from a file crontab mycron

Example: Adding a Cron Job

crontab -e

Add the following line to schedule a daily backup at 2 AM:

0 2 * * * /usr/bin/backup-script.sh
Note: The cron schedule format is MIN HOUR DAY MONTH DOW. Each field can be a number, asterisk (*), or a list of values separated by commas.
Warning: Ensure that the script path is absolute and the script has execute permissions.

2. Listing Cron Jobs

Command Description Notes
crontab -l List cron jobs for the current user Displays all entries in the user's crontab file
sudo crontab -l -u username List cron jobs for a specific user Requires root privileges to view other users' crontabs
ls /var/spool/cron/ List all user cron files Shows cron job files for each user on the system
cat /var/spool/cron/username View raw content of a user's cron file Direct file access to inspect cron job definitions

Example: Listing Cron Jobs for Current User

crontab -l
Note: The crontab -l command lists all cron jobs in the format specified by the crontab syntax. Each line represents a scheduled task.

3. Removing Crontab

Action Command Description
Remove all cron jobs for current user crontab -r Deletes the entire crontab file for the current user
Remove all cron jobs with confirmation crontab -r -i Prompts before deleting the crontab file
Remove specific crontab file crontab -r -f /path/to/crontab Deletes a specific crontab file by path (if supported)
Note: The -r flag removes all entries from the crontab. Use with caution as this action is irreversible without a backup.

4. Understanding Cron Syntax

Field Allowed Values Description
Minute 0-59 Specifies the minute of the hour (0-59)
Hour 0-23 Specifies the hour of the day (0-23)
Day of Month 1-31 Specifies the day of the month (1-31)
Month 1-12 or jan-dec Specifies the month of the year (1-12 or jan-dec)
Day of Week 0-7 or sun-sat Specifies the day of the week (0-7 or sun-sat)
Command Any valid command The command to execute

Example: Cron Expression Breakdown

* * * * * /path/to/script.sh
  • * in the first field means "every minute"
  • * in the second field means "every hour"
  • * in the third field means "every day of the month"
  • * in the fourth field means "every month"
  • * in the fifth field means "every day of the week"

Example: Running a Script Every Hour at 15 Minutes

15 * * * * /usr/bin/python3 /home/user/backup.py
  • Run at minute 15 of every hour
  • Command: /usr/bin/python3 /home/user/backup.py

Example: Weekly Backup on Sundays at 2 AM

0 2 * * 0 /usr/bin/backup.sh
  • Run at 2:00 AM on Sundays (day of week = 0)
  • Command: /usr/bin/backup.sh

5. Using Special Time Strings

String Meaning Example
@reboot Run once at startup * * * * * /path/to/script.sh
@yearly Run once a year (0 0 1 1 *) @yearly /path/to/script.sh
@annually Same as @yearly @annually /path/to/script.sh
@monthly Run once a month (0 0 1 *) @monthly /path/to/script.sh
@weekly Run once a week (0 0 * * 0) @weekly /path/to/script.sh
@daily Run once a day (0 0 *) @daily /path/to/script.sh
@midnight Same as @daily @midnight /path/to/script.sh
@hourly Run once an hour (0 *) @hourly /path/to/script.sh

Example: Using @daily

@daily /home/user/backup.sh

Example: Using @reboot

@reboot /home/user/init.sh

6. Managing System Cron

Aspect Description Notes
Service Status systemctl status cron Check if cron service is running
Start Service systemctl start cron Start the cron service
Enable Service systemctl enable cron Ensure cron starts on boot
Restart Service systemctl restart cron Restart the cron daemon
Reload Configuration systemctl reload cron Re-read configuration without restart

Example: Check Cron Service Status

$ systemctl status cron
● cron.service - Regular background program processing daemon
   Loaded: loaded (/lib/systemd/system/cron.service; enabled; vendor preset: enabled)
   Active: active (running) since Mon 2025-04-01 10:00:00 UTC; 1h 25min ago
     Docs: man:cron(8)
   Main PID: 1234 (cron)
      Tasks: 1 (limit: 4915)
   CGroup: /system.slice/cron.service
           └─1234 /usr/sbin/cron -f
Note: On some systems, the service name might be cron, crond, or anacron. Ensure the correct service name is used.

Example: Enable Cron to Start on Boot

$ sudo systemctl enable cron
Created symlink /etc/systemd/system/multi-user.target.wants/cron.service → /lib/systemd/system/cron.service.
Warning: Disabling or stopping the cron service will prevent all scheduled tasks from running. Ensure that any critical automated jobs are either disabled or migrated before making changes.

7. Using Cron Directories

Cron directories provide a way to manage multiple cron jobs by organizing them into separate files within dedicated directories. This approach is particularly useful for systems with many scheduled tasks, as it improves organization and maintainability.

Directory Description Usage
/etc/cron.d/ System-wide cron jobs that require a user specification Place files here to define jobs for specific users or system-wide tasks
/etc/cron.daily/ Jobs to be run once per day Scripts or commands in this directory are executed daily by the cron daemon
/etc/cron.weekly/ Jobs to be run once per week Scripts or commands in this directory are executed weekly by the cron daemon
/etc/cron.monthly/ Jobs to be run once per month Scripts or commands in this directory are executed monthly by the cron daemon

Example: Creating a Daily Cron Job

To create a daily job, place a script or command in /etc/cron.daily/ with appropriate permissions:

#!/bin/bash
# /etc/cron.daily/system-backup.sh

echo "Starting system backup at $(date)" >> /var/log/backup.log
# Backup logic here...
Note: Cron directories do not require a user field in the crontab format. The system automatically runs scripts in these directories according to their schedule.

8. Viewing Cron Logs

Log Location Content Notes
/var/log/cron /var/log/cron Standard log file for cron job execution (may vary by distribution)
/var/log/syslog /var/log/syslog System log that includes cron job entries (common on Ubuntu/Debian)
/var/log/messages /var/log/messages System messages log (used on some Red Hat-based systems)

Example: Check cron logs for recent entries

# View last 10 entries in cron log
tail -n 10 /var/log/cron

# View cron logs with timestamp and search for specific job
grep "job_name" /var/log/syslog | tail -n 5
Note: The exact location and format of cron logs can vary between Linux distributions. Some systems may require enabling logging in /etc/rsyslog.conf or similar configuration files.

Example: Enable detailed cron logging (syslog)

# Edit rsyslog configuration to log cron details
echo ":programname, isequal, "CRON" ~" >> /etc/rsyslog.conf

# Restart rsyslog to apply changes
systemctl restart rsyslog

9. Scheduling with anacron

Option Values Description
anacron /etc/anacrontab Configuration file for anacron jobs
period daily, weekly, monthly How often the job should run
delay 5 Minutes to delay before starting the job

Example: Basic anacron job

/etc/anacrontab

# Period   Delay   Job-identifier   Command
daily      5       backup-job       /usr/bin/backup.sh
Note: anacron is ideal for systems that are not always running, as it ensures jobs run even if the system was offline during their scheduled time.

10. Using at for One-Time Tasks

Command Description Example
at Schedule a one-time task to run at a specified time at 14:30
at -f <file> Schedule a script or command from a file at -f /path/to/script.sh 15:00
at -l List all pending at jobs at -l
at -r <job_id> Remove a pending at job at -r 1

Example: Schedule a One-Time Task

echo "echo 'Hello World' &gt; /tmp/hello.txt" | at 14:30
Note: The at command requires the at daemon to be running. On most systems, it's started automatically at boot.
Warning: The at command does not support cron-style time specifications like * * * * *. You must specify a specific time or date.

11. Scheduling with systemd Timers

systemd timers are a modern alternative to traditional cron jobs, offering better integration with the systemd init system and more flexible scheduling capabilities.

Property Description Example
[Timer] Section containing timer-specific settings [Timer]
OnCalendar Schedules the timer based on calendar events OnCalendar=*:0/15
OnBootSec Time to wait after boot before running the timer OnBootSec=10min
OnStartupSec Time to wait after startup before running the timer OnStartupSec=5min
OnUnitActiveSec Time to wait after unit activation before running the timer OnUnitActiveSec=1h
AccuracySec Maximum accuracy for timer scheduling AccuracySec=1min

Example: Basic systemd timer configuration

[Unit]
Description=Run backup script every hour

[Timer]
OnCalendar=hourly
AccuracySec=1min

[Service]
Type=oneshot
ExecStart=/usr/local/bin/backup.sh
Note: systemd timers are managed by the systemd service manager and can be enabled/disabled using systemctl enable timer-name.timer.
Warning: Ensure that the user running the timer has appropriate permissions to execute the specified command or script.

Was this article helpful?