
The Clockwork Server: Cron and Systemd Timers
Schedule your success. Learn to automate recurring tasks in Linux. Master the legendary 'Crontab' syntax and explore the modern, high-precision 'Systemd Timers'. Understand when to use each for backups and system maintenance.
Automation: Scheduling Recurring Tasks
A human admin should never have to manually run a backup or clear out old logs. If a task needs to be done more than once, it should be scheduled. In Linux, we have two primary "Clocks" for this:
- Cron: The classic, simple, and universal scheduler. It has been the standard for 40 years.
- Systemd Timers: The modern, robust alternative. It is harder to set up but provides better logging and handles "Missed" events (like if the server was off when the task was supposed to run).
In this lesson, we will master the art of the schedule.
1. The Classic: Cron
Cron is a background daemon that checks a table of tasks every minute. This table is called a Crontab.
The Crontab Syntax:
A crontab line has 5 time fields followed by the command:
* * * * * command_to_run
| Field | Range | Meaning |
|---|---|---|
| 1. Minute | 0 - 59 | When in the hour. |
| 2. Hour | 0 - 23 | When in the day. |
| 3. Day of Month | 1 - 31 | Which day. |
| 4. Month | 1 - 12 | Which month. |
| 5. Day of Week | 0 - 6 | Sunday is 0. |
Common Examples:
30 2 * * * /path/to/backup.sh: Run every day at 2:30 AM.0 0 * * 1 /scripts/weekly.sh: Run every Monday at midnight.*/15 * * * * /scripts/check.sh: Run every 15 minutes.
Managing your Crontab:
# Edit your personal crontab
crontab -e
# List your scheduled tasks
crontab -l
2. The Modern: Systemd Timers
If Cron is a simple alarm clock, a Systemd Timer is a professional scheduling system.
Why use Timers over Cron?
- Missed Events: If the server is off, a timer can run the task immediately upon reboot (using
Persistent=true). - Dependencies: You can say "Only run this timer if the database service is active."
- Logging: Timer tasks appear in
journalctl. Cron logs are notoriously hard to find.
The Two-File Setup:
- The Service (
backup.service): Defines What to run. - The Timer (
backup.timer): Defines When to run it.
# backup.timer
[Unit]
Description=Run daily backup
[Timer]
OnCalendar=daily
Persistent=true
[Install]
WantedBy=timers.target
3. The "Standard" Times
You don't always have to write complex syntax. Many systems include folders where you can just drop a script to have it run at set intervals:
/etc/cron.daily//etc/cron.weekly//etc/cron.monthly/
4. Practical: The Self-Cleaning Log Script
Let's write a simple script and schedule it to run every Sunday to delete logs older than 30 days.
#!/bin/bash
# clean_logs.sh
find /var/log/myapp -name "*.log" -mtime +30 -delete
The Crontab entry:
0 0 * * 0 /home/sudeep/scripts/clean_logs.sh
5. Avoiding the "Environment" Trap
The #1 reason scripts fail in Cron but work in your terminal is The PATH.
- In your terminal, you have a rich shell environment.
- In Cron, the environment is almost empty.
The Fix: Always use absolute paths in your scripts and crontabs!
- Wrong:
python3 script.py - Right:
/usr/bin/python3 /home/sudeep/script.py
6. Example: A Crontab Syntax Generator (Python)
Crontab syntax is notoriously confusing for beginners. Here is a Python script that asks for human-readable input and generates the correct Cron string.
def generate_cron_string():
"""
Interactively builds a cron schedule.
"""
print("--- Cron Syntax Helper ---")
minute = input("Minute (0-59 or *): ") or "*"
hour = input("Hour (0-23 or *): ") or "*"
day = input("Day of Month (1-31 or *): ") or "*"
month = input("Month (1-12 or *): ") or "*"
weekday = input("Day of Week (0-6, 0=Sun or *): ") or "*"
command = input("Full path to command: ")
cron_str = f"{minute} {hour} {day} {month} {weekday} {command}"
print("\nYour Crontab Line:")
print("-" * 30)
print(cron_str)
print("-" * 30)
print("To install: Copy and paste into 'crontab -e'")
if __name__ == "__main__":
generate_cron_string()
7. Professional Tip: Use 'anacron' for Desktops
If you are using a laptop that you turn off at night, your "daily" Cron tasks at 2:00 AM will never run. Use anacron. It is designed for computers that aren't on 24/7. It tracks when a task was last run and catches up as soon as you turn the machine on.
8. Summary
Scheduling is the key to a quiet life as an administrator.
Cronis simple and everywhere.Systemd Timersare robust, loggable, and survivable.- Always use Absolute Paths (
/usr/bin/python3instead ofpython3). - Use
crontab -lto audit your scheduled tasks. - Use Persistent=true in timers for tasks that must run even if the machine was off.
In the next lesson, we will look at the machine's "Wake Up" routine: Understanding the Boot Sequence and Targets.
Quiz Questions
- What does the cron schedule
0 */2 * * *mean? - Why do scripts often fail when run by cron even though they work manually in the terminal?
- What is the benefit of a
systemd.timerover a standard crontab?
Continue to Lesson 4: Boot Sequence and Targets—Understanding System Readiness.