Skip to content
Go back

Schedule Tasks with Precision with Cron Jobs

Published:

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

πŸ› οΈ Cron Syntax Format

* * * * * /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:

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:


✍️ 2. Set the MAILTO Variable in Your Crontab

Open your crontab:

crontab -e

At the top, add:

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:

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

πŸ”§ 4. Test It

Create a simple script:

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


βœ… 3. Configure msmtp

Create a config file:

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

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

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!

chmod 600 ~/.config/msmtp/config

βœ… 4. Set msmtp as the Mailer

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

nano ~/.mailrc

Add:

set sendmail="/usr/bin/msmtp"
set use_from=yes
set realname="Your Name"
set [email protected]

βœ… 5. Test the Setup

Run this command:

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

Check your Gmail inbox!


βœ… 6. Add to Crontab

Edit your crontab:

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



Suggest Changes

Previous Post
Linux-M3 - Introduction to Shell Scripting
Next Post
Linux-M1 - Introduction to Linux