Cron Jobs: Automated Tasks

Cron jobs allow you to execute commands or scripts automatically based on a defined schedule. They are used for backups, cleanup, updates, sending emails and much more.

02

Modify the crontab

Each user has their own crontab. To modify it:

bash
crontab -e

The first time it will ask which editor to use (choose nano if unsure).

To view active cron jobs:

bash
crontab -l

To delete all cron jobs:

bash
crontab -r
03

Crontab syntax

# ┌───────── minute (0-59) # │ ┌───────── hour (0-23) # │ │ ┌───────── day of month (1-31) # │ │ │ ┌───────── month (1-12) # │ │ │ │ ┌───────── day of week (0=Sunday, 6=Saturday) # │ │ │ │ │ # * * * * * command

Practical examples

bash
# Every minute

# Every hour (at minute 0)
0 * * * * /path/script.sh

# Every day at 03:00
0 3 * * * /path/script.sh

# Every Monday at 08:30
30 8 * * 1 /path/script.sh

# First of the month at midnight
0 0 1 * * /path/script.sh

# Every 5 minutes
*/5 * * * * /path/script.sh

# Every 6 hours
0 */6 * * * /path/script.sh

# Monday-Friday at 09:00
0 9 * * 1-5 /path/script.sh
  • /path/script.sh
04

Real-world usage examples

Database backup every night at 02:00

bash
0 2 * * * mysqldump -u root -pPASSWORD database > /backups/db_$(date +\%Y\%m\%d).sql

Clean up logs every Sunday

bash
0 4 * * 0 journalctl --vacuum-time=30d

Automatic SSL renewal

bash
0 3 * * * certbot renew --quiet

Synchronize with rsync every hour

bash
0 * * * * rsync -az /var/www/ backup@IP_BACKUP:/backups/www/

Automatically restart a service if down

bash
*/5 * * * * systemctl is-active --quiet nginx || systemctl restart nginx
05

Save the output of cron jobs

By default cron job output is sent via email to the system user. To save it to a file:

bash
# Save stdout and stderr to file
0 3 * * * /path/script.sh >> /var/log/my-cron.log 2>&1

# Discard all output
0 3 * * * /path/script.sh > /dev/null 2>&1
06

System crontab

Besides user crontab, you can use files in /etc/cron.d/ or these directories:

Just put an executable script in these directories:

bash
nano /etc/cron.daily/my-backup
chmod +x /etc/cron.daily/my-backup
  • /etc/cron.hourly/: scripts run every hour
  • /etc/cron.daily/: scripts run every day
  • /etc/cron.weekly/: scripts run every week
  • /etc/cron.monthly/: scripts run every month
07

Verify that cron works

bash
# See cron logs (Debian/Ubuntu)
grep CRON /var/log/syslog | tail -20

# With journald
journalctl -u cron -n 20

# Verify the service is active
systemctl status cron     # Debian/Ubuntu
systemctl status crond    # CentOS/AlmaLinux
08

Online tool to generate cron

If you don't remember the syntax, use crontab.guru to generate and verify cron expressions visually.

DeluxHost, founded in 2023, offers high-quality hosting solutions for various digital needs. We provide shared hosting, VPS, and dedicated servers with advanced security and global data centers.

© DeluxHost, All rights reserved. | VAT Number : IT17734661006
All Systems Operational