Scheduled tasks
Table of contents
- Introduction to cron
- crontab syntax
- Examples of common tasks
- anacron for non-24/7 machines
- systemd timers
- Hands-on exercises
1 - Introduction to cron
What is cron?
cron is the standard task scheduler on Linux. It runs commands at specific times.
Types of crontab
| File | Scope | Editing |
|---|---|---|
| User crontab | Per user | crontab -e |
/etc/crontab | System | direct editing |
/etc/cron.d/* | System (files) | direct editing |
/etc/cron.daily/ | Daily scripts | drop a script |
/etc/cron.hourly/ | Hourly scripts | drop a script |
Manage your crontab
# Éditer son crontab
crontab -e
# Lister son crontab
crontab -l
# Supprimer son crontab
crontab -r
# Éditer le crontab d'un autre utilisateur (root)
sudo crontab -u john -e
🔝 Back to table of contents
2 - crontab syntax
Format
┌───────────── minute (0 - 59)
│ ┌───────────── heure (0 - 23)
│ │ ┌───────────── jour du mois (1 - 31)
│ │ │ ┌───────────── mois (1 - 12)
│ │ │ │ ┌───────────── jour de la semaine (0 - 7, 0 ou 7 = dimanche)
│ │ │ │ │
* * * * * commande à exécuter
Special characters
| Character | Meaning |
|---|---|
* | All values |
, | List of values |
- | Range of values |
/ | Step (interval) |
Scheduling examples
| Cron | Meaning |
|---|---|
0 * * * * | Every hour (minute 0) |
0 0 * * * | Every day at midnight |
30 8 * * * | Every day at 8:30 |
0 0 * * 0 | Every Sunday at midnight |
0 0 1 * * | The 1st of each month |
*/15 * * * * | Every 15 minutes |
0 9-18 * * 1-5 | Every hour from 9 to 18, Monday-Friday |
0 0,12 * * * | At midnight and noon |
@reboot | At startup |
Shortcuts
| Shortcut | Equivalent |
|---|---|
@reboot | At startup |
@yearly | 0 0 1 1 * |
@monthly | 0 0 1 * * |
@weekly | 0 0 * * 0 |
@daily | 0 0 * * * |
@hourly | 0 * * * * |
Environment variables
# En haut du crontab
SHELL=/bin/bash
PATH=/usr/local/bin:/usr/bin:/bin
[email protected]
# Puis les tâches
0 * * * * /scripts/backup.sh
🔝 Back to table of contents
3 - Examples of common tasks
Daily backup
# Tous les jours à 2h du matin
0 2 * * * /usr/local/bin/backup.sh >> /var/log/backup.log 2>&1
Log cleanup
# Tous les dimanches à 3h
0 3 * * 0 find /var/log -name "*.log" -mtime +30 -delete
Synchronization
# Toutes les 6 heures
0 */6 * * * rsync -avz /data/ backup@remote:/backup/
Monitoring
# Toutes les 5 minutes
*/5 * * * * /scripts/check_services.sh
Complete backup script
#!/bin/bash
# /usr/local/bin/backup.sh
DATE=$(date +%Y%m%d_%H%M%S)
BACKUP_DIR="/backup"
SOURCE="/var/www"
# Créer le backup
tar -czf "$BACKUP_DIR/www_$DATE.tar.gz" "$SOURCE"
# Garder seulement les 7 derniers
find "$BACKUP_DIR" -name "www_*.tar.gz" -mtime +7 -delete
echo "Backup completed: $DATE"
Best practices
# 1. Toujours rediriger la sortie
0 * * * * /script.sh >> /var/log/script.log 2>&1
# 2. Utiliser des chemins absolus
0 * * * * /usr/bin/python3 /home/user/script.py
# 3. Verrouiller pour éviter les exécutions multiples
*/5 * * * * flock -n /tmp/script.lock /script.sh
tip
Use crontab.guru to visualize and test your cron expressions!
🔝 Back to table of contents
4 - anacron for non-24/7 machines
The problem with cron
cron does not catch up on missed tasks if the machine was turned off.
The solution: anacron
anacron runs the missed tasks at the next startup.
# /etc/anacrontab
SHELL=/bin/sh
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
# period delay identifier command
1 5 daily run-parts /etc/cron.daily
7 10 weekly run-parts /etc/cron.weekly
@monthly 15 monthly run-parts /etc/cron.monthly
| Field | Description |
|---|---|
| period | Frequency in days |
| delay | Delay in minutes after startup |
| identifier | Unique name |
| command | Command to run |
System directories
Simply drop your scripts into:
/etc/cron.daily/ # Exécutés quotidiennement
/etc/cron.weekly/ # Exécutés hebdomadairement
/etc/cron.monthly/ # Exécutés mensuellement
# Exemple : script de nettoyage
sudo nano /etc/cron.daily/clean-tmp
#!/bin/bash
find /tmp -type f -mtime +7 -delete
# Rendre exécutable
sudo chmod +x /etc/cron.daily/clean-tmp
🔝 Back to table of contents
5 - systemd timers
A modern alternative to cron
systemd timers offer more features.
Structure
A timer requires two files:
- A
.timerfile (scheduling) - A
.servicefile (action)
Example: daily backup
The service:
# /etc/systemd/system/backup.service
[Unit]
Description=Daily Backup
[Service]
Type=oneshot
ExecStart=/usr/local/bin/backup.sh
The timer:
# /etc/systemd/system/backup.timer
[Unit]
Description=Run backup daily
[Timer]
OnCalendar=*-*-* 02:00:00
Persistent=true
[Install]
WantedBy=timers.target
Enable the timer
# Recharger systemd
sudo systemctl daemon-reload
# Activer et démarrer
sudo systemctl enable --now backup.timer
# Vérifier
sudo systemctl list-timers
OnCalendar syntax
| Expression | Meaning |
|---|---|
*-*-* 02:00:00 | Every day at 2:00 |
Mon *-*-* 10:00:00 | Every Monday at 10:00 |
*-*-01 00:00:00 | The 1st of each month |
hourly | Every hour |
daily | Every day |
weekly | Every week |
Useful options
| Option | Description |
|---|---|
OnCalendar | Absolute scheduling |
OnBootSec | After startup |
OnUnitActiveSec | After the last run |
Persistent=true | Catches up on missed runs |
RandomizedDelaySec | Random delay |
Useful commands
# Lister les timers
systemctl list-timers
# Statut d'un timer
systemctl status backup.timer
# Logs de l'exécution
journalctl -u backup.service
# Exécuter manuellement
sudo systemctl start backup.service
🔝 Back to table of contents
6 - Hands-on exercises
Exercise 1: First crontab
# 1. Ouvrez votre crontab
crontab -e
# 2. Ajoutez une tâche de test (toutes les minutes)
* * * * * echo "Test $(date)" >> /tmp/cron_test.log
# 3. Attendez 2 minutes puis vérifiez
cat /tmp/cron_test.log
# 4. Supprimez la tâche
crontab -e
# (supprimez la ligne)
Exercise 2: Monitoring script
# 1. Créez le script
cat << 'EOF' | sudo tee /usr/local/bin/disk_check.sh
#!/bin/bash
USAGE=$(df -h / | awk 'NR==2 {print $5}' | sed 's/%//')
if [ "$USAGE" -gt 80 ]; then
echo "ALERTE: Disque à $USAGE% - $(date)" >> /var/log/disk_alert.log
fi
EOF
sudo chmod +x /usr/local/bin/disk_check.sh
# 2. Ajoutez au crontab (toutes les heures)
crontab -e
# 0 * * * * /usr/local/bin/disk_check.sh
Exercise 3: Understand the syntax
What do these expressions mean?
30 4 * * *0 */2 * * *0 9-17 * * 1-50 0 1,15 * *
Answers
- Every day at 4:30
- Every 2 hours, at minute 0
- Every hour from 9 to 17, Monday through Friday
- The 1st and the 15th of each month at midnight
Quiz
Q1. How do you edit your crontab?
Answer
crontab -e
Q2. What does */15 * * * * mean?
Answer
Every 15 minutes
Q3. What is the advantage of systemd timers over cron?
Answer
Integration with journald (logs), Persistent (catch-up), more flexibility
🔝 Back to table of contents
Key takeaways
- crontab -e to edit, crontab -l to list
- Format:
minute hour day month day_of_week command - Always redirect the output (
>> logfile 2>&1) - Use absolute paths
- anacron for machines that don't run 24/7
- systemd timers = modern alternative with more features
- Test with crontab.guru
🔝 Back to table of contents
← Previous chapter | Next chapter: Archiving and compression →