Post

Schedule Tasks with Precision with Cron Jobs

Cron Jobs Cheat Sheet, Email Notification from Cron Jobs, Send Cron Job Emails via Gmail SMTP

Schedule Tasks with Precision with Cron Jobs

πŸ“… Cron Jobs Cheat Sheet: Schedule Tasks with Precision

πŸ› οΈ Cron Syntax Format

1
2
3
4
5
6
7
* * * * * /path/to/command arg1 arg2
β”‚ β”‚ β”‚ β”‚ β”‚
β”‚ β”‚ β”‚ β”‚ └───── Day of the Week (0 - 7) (Sunday = 0 or 7)
β”‚ β”‚ β”‚ └──────── Month (1 - 12)
β”‚ β”‚ └──────────── Day of the Month (1 - 31)
β”‚ └──────────────── Hour (0 - 23)
└──────────────────── Minute (0 - 59)

πŸ” Special Time Strings

StringMeaningEquivalent To
@rebootRun once, at startup-
@yearlyOnce a year0 0 1 1 *
@annuallySame as @yearly0 0 1 1 *
@monthlyOnce a month0 0 1 * *
@weeklyOnce a week0 0 * * 0
@dailyOnce a day0 0 * * *
@midnightSame as @daily0 0 * * *
@hourlyOnce an hour0 * * * *

πŸ“‹ Common Cron Job Examples

πŸ“‚ File & Directory Tasks

TaskCron ScheduleCommand
Backup /home daily at 2 AM0 2 * * *tar -czf /backup/home.tar.gz /home
Clean tmp folder every day at midnight0 0 * * *rm -rf /tmp/*
Sync files every 10 minutes*/10 * * * *rsync -av /source /destination

πŸ’Ύ System Maintenance

TaskCron ScheduleCommand
Update package list daily at 1 AM0 1 * * *sudo apt update
Reboot system every Sunday at 4 AM0 4 * * 0sudo reboot
Monitor disk usage every 30 min*/30 * * * *df -h >> /var/log/disk_usage.log

πŸ§ͺ Script Execution

TaskCron ScheduleCommand
Run a script at 3 PM every day0 15 * * */home/user/myscript.sh
Run script on the first day of the month0 0 1 * *bash /path/to/monthly_task.sh
Run every 5 minutes*/5 * * * */home/user/script.sh

πŸ“ˆ Logging & Monitoring

TaskCron ScheduleCommand
Append date to file every Sunday at 6:15 PM15 18 * * 0date >> /home/user/sundays.txt
Log user sessions daily at midnight0 0 * * *who >> /var/log/user_sessions.log

πŸ“§ Email Notification

To send output to your email, add this to the top of your crontab:

1
MAILTO="[email protected]"

Example:

0 9 * * * /path/to/backup.sh

βš™οΈ Crontab Commands

CommandDescription
crontab -eEdit current user’s crontab
crontab -lList current user’s crontab
crontab -rRemove current user’s crontab
crontab -u [user] -lList another user’s crontab (as root)
crontab -u [user] -eEdit another user’s crontab (as root)

πŸ“¬ Step-by-Step Guide: Email Notification from Cron Jobs

βœ… 1. Install a Mail Transfer Agent (MTA)

You need an MTA like mailutils or sendmail:

  • Ubuntu/Debian:

    1
    2
    
    sudo apt update
    sudo apt install mailutils
    
  • CentOS/RHEL/Fedora:

    1
    
    sudo yum install mailx
    
  • Arch Linux:

    1
    
    sudo pacman -S mailutils
    

✍️ 2. Set the MAILTO Variable in Your Crontab

Open your crontab:

1
crontab -e

At the top, add:

1
MAILTO="[email protected]"

Then write a cron job below it. For example:

MAILTO="[email protected]"
0 5 * * * /home/user/backup.sh

This will send standard output (stdout) and standard error (stderr) of backup.sh to your email.


πŸ“ 3. Ensure Your Script Produces Output

Only scripts that generate output will trigger emails.

Example script:

1
2
3
4
#!/bin/bash
echo "Backup started at $(date)"
tar -czf /backup/home.tar.gz /home
echo "Backup completed."

πŸ”§ 4. Test It

Create a simple script:

1
2
echo -e '#!/bin/bash\necho "Test email from cron at $(date)"' > ~/testcron.sh
chmod +x ~/testcron.sh

Add to crontab:

MAILTO="[email protected]"
*/2 * * * * /home/yourusername/testcron.sh

Check your email after 2–3 minutes.


πŸ›  Troubleshooting

ProblemSolutionΒ 
Not receiving mailCheck your spam folder. Also try running the command manually and verify it produces output.Β 
Cron not sending mailEnsure mailutils is installed. Try `echo β€œbody” | mail -s β€œSubject” [email protected]` to test manually.Β 
External SMTP neededUse tools like msmtp, sSMTP, or configure postfix with Gmail SMTP.Β 

πŸ“¬ Step-by-Step: Send Cron Job Emails via Gmail SMTP


βœ… 1. Create an App Password in Gmail

Gmail no longer allows direct login from less secure apps. You must use an App Password.

Steps:

  1. Go to https://myaccount.google.com/
  2. Enable 2-Step Verification if not already enabled.
  3. Go to Security > App passwords
  4. Generate a new password (select β€œOther”, name it cronmail, click β€œGenerate”)
  5. Copy the 16-character password β€” you’ll need this soon

βœ… 2. Install msmtp and msmtp-mta

  • Debian/Ubuntu:

    1
    
    sudo apt install msmtp msmtp-mta
    
  • Arch Linux:

    1
    
    sudo pacman -S msmtp
    
  • Fedora/RHEL:

    1
    
    sudo dnf install msmtp
    

βœ… 3. Configure msmtp

Create a config file:

1
2
mkdir -p ~/.config/msmtp
nano ~/.config/msmtp/config

Paste this into the file (replace with your Gmail info):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
defaults
auth           on
tls            on
tls_trust_file /etc/ssl/certs/ca-certificates.crt
logfile        ~/.config/msmtp/msmtp.log

account        gmail
host           smtp.gmail.com
port           587
from           [email protected]
user           [email protected]
password       your_app_password

account default : gmail

Replace [email protected] and your_app_password accordingly.

πŸ›‘ Important: Secure the file!

1
chmod 600 ~/.config/msmtp/config

βœ… 4. Set msmtp as the Mailer

Ensure mail command uses msmtp. Create or edit this file:

1
nano ~/.mailrc

Add:

1
2
3
4
set sendmail="/usr/bin/msmtp"
set use_from=yes
set realname="Your Name"
set from=[email protected]

βœ… 5. Test the Setup

Run this command:

1
echo "This is a test from msmtp" | mail -s "Test Email" [email protected]

Check your Gmail inbox!


βœ… 6. Add to Crontab

Edit your crontab:

1
crontab -e

Add this:

MAILTO="[email protected]"
* * * * * echo "Hello from cron at $(date)"

Check if you receive an email every minute.


πŸ› οΈ Troubleshooting

IssueFix
No email receivedCheck Gmail spam folder. Check ~/.config/msmtp/msmtp.log for logs.
TLS errorsMake sure ca-certificates package is installed and path to certs is correct.
Cron output not triggering emailEnsure the command prints output (stdout or stderr).

🧠 Tips

  • Use full paths to commands and scripts.
  • Redirect output to a log: command >> /path/to/logfile.log 2>&1
  • Test cron expressions with: https://crontab.guru

This post is licensed under CC BY 4.0 by the author.