Skip to content

Latest commit

Β 

History

History
161 lines (106 loc) Β· 2.48 KB

File metadata and controls

161 lines (106 loc) Β· 2.48 KB

⏰ Cron & Scheduling in Bash


πŸ”Ή 1. What is Cron?

  • cron = time-based job scheduler in Unix/Linux.
  • Runs background process crond to execute commands or scripts at scheduled times.
  • Jobs are defined in crontab (cron table).

πŸ”Ή 2. Crontab Format

Each cron job has 5 fields + command:

* * * * * command-to-execute
| | | | |
| | | | └── Day of week (0-6, Sun=0)
| | | └──── Month (1-12)
| | └────── Day of month (1-31)
| └──────── Hour (0-23)
└────────── Minute (0-59)

πŸ”Ή 3. Examples

Every minute

* * * * * echo "Hello" >> /tmp/hello.log

Every day at 2:30 AM

30 2 * * * /home/user/backup.sh

Every Monday at 5 PM

0 17 * * 1 /home/user/report.sh

Every 10 minutes

*/10 * * * * /home/user/script.sh

At reboot

@reboot /home/user/startup.sh

πŸ”Ή 4. Special Keywords

Instead of 5 fields, you can use shortcuts:

Keyword Meaning
@reboot Run at system startup
@yearly Once a year (Jan 1, 00:00)
@monthly Once a month
@weekly Once a week
@daily Once a day (midnight)
@hourly Once every hour

πŸ”Ή 5. Managing Cron Jobs

Edit your crontab

crontab -e

List your cron jobs

crontab -l

Remove all cron jobs

crontab -r

πŸ”Ή 6. Scheduling a Script

  1. Write your script, e.g. /home/user/backup.sh
#!/bin/bash
tar -czf /home/user/backups/backup_$(date +%F).tar.gz /home/user/data
  1. Make it executable:
chmod +x /home/user/backup.sh
  1. Add to cron (e.g., daily at 1 AM):
0 1 * * * /home/user/backup.sh

πŸ”Ή 7. Logging & Debugging

  • Redirect output/errors to log:
0 3 * * * /home/user/myscript.sh >> /var/log/myscript.log 2>&1
  • Check logs:
journalctl -u cron
# or
grep CRON /var/log/syslog   # Debian/Ubuntu
grep CROND /var/log/cron    # RHEL/CentOS

πŸ”Ή 8. One-Time Scheduling with at

If you want a command once, use at:

echo "/home/user/script.sh" | at 10:30

πŸ‘‰ Runs once at 10:30 AM today.


βœ… Summary:

  • Use cron for repetitive scheduling.
  • Use @keywords for simple scheduling.
  • Use at for one-time jobs.
  • Always log output for debugging.