Lesson 3: The Clockwork (Scheduled Tasks with Cron)
What if your script needs to run at 2 AM every night? You can't set an alarm and wake up to type the command. This is where Cron comes in — Linux's built-in task scheduler.
What is Cron?
Cron is a daemon (background service) that runs scheduled tasks. Each task is defined in a crontab (cron table).
The Cron Syntax
A cron schedule has five fields:
┌───────────── minute (0 - 59)
│ ┌───────────── hour (0 - 23)
│ │ ┌───────────── day of month (1 - 31)
│ │ │ ┌───────────── month (1 - 12)
│ │ │ │ ┌───────────── day of week (0 - 7, Sun = 0 or 7)
│ │ │ │ │
* * * * * command_to_run
Common Examples
| Schedule | Meaning |
|----------|---------|
| 0 2 * * * | Every day at 2:00 AM |
| */5 * * * * | Every 5 minutes |
| 0 0 * * 0 | Every Sunday at midnight |
| 30 9 1 * * | 9:30 AM on the 1st of every month |
| 0 */6 * * * | Every 6 hours |
Managing Cron Jobs
crontab -l # List your scheduled jobs
crontab -e # Edit your cron schedule
crontab -r # Remove ALL your cron jobs (dangerous!)
System-Wide Cron Directories
Linux also has pre-built folders for common schedules:
/etc/cron.hourly/— Scripts here run every hour./etc/cron.daily/— Scripts here run once a day./etc/cron.weekly/— Scripts here run once a week.
Mission Objective
Set up your first automated task:
- Check the clock: Run
crontab -lto see if any jobs are already scheduled. - Build the task: Create a logger script with
echo '#!/bin/bash\ndate >> /tmp/cron_log.txt' > /tmp/logger.sh && chmod +x /tmp/logger.sh. - Explore the system: Run
ls /etc/cron*to see the system-wide cron directories.
Real-World Usage
Cron jobs power everything from database backups to SSL certificate renewals (Certbot uses cron!) to log cleanup and health checks.