Cron

Purpose

cron is a great tool to schedule repetitive tasks. For example, let's assume we have to run the following script which is located at /home/user/backup/dump.sh

#!/bin/bash

$ cd /home/backups
$ mongodump --forceTableScan --uri "mongodb+srv://<username>:<password>@cluster0.a2zef.mongodb.net/<databasename>" --out `date +"%Y-%m-%d"` --gzip

This file is an example of dumping the mongodb data into bson format.

crontab -e

Now let's look at how we can make it run after specific period each day so that we don't have to manually take back up.


$ crontab -e #it will open up the editor choice if open for the first time. Or else, it will open up the file.

$ 0 3 * * * /bin/sh /home/user/backup/dump.sh #exit from nano/vim/other editor

$ sudo cron restart

cron schedule format

The format of the crontab file is:

MIN HOUR DOM MON DOW CMD

ShortDescriptionValues
MINMinute field0 to 59
HOURHour field0 to 23
DOMDay of Month1-31
MONMonth field1-12
DOWDay Of Week0-6
CMDCommandAny command to be executed.

crontab -l to list all the cron jobs available for the user.

crontab -r will remove all the cron jobs set by that user.

Mailing the output of the cron job.

In order to send the cron output to via mail, you'll need to setup smtp client.

sudo apt update
sudo apt install ssmtp mailutils

Configure SMTP

Edit the config file:

sudo nano /etc/ssmtp/ssmtp.conf

Next, fill the appropriate information in the conf file

root=your@gmail.com #your mail id
mailhub=smtp.gmail.com #mail provider
FromLineOverride=YES
hostname=hostname #(you can put anything here)
AuthUser=your@gmail.com #your mail id
AuthPass=password #your app password generated from https://myaccount.google.com/apppasswords
FromLineOverride=YES
UseSTARTTLS=YES

Note

The password of your gmail account ID won't work while sending mails.

You'll require to generate one in Google app passwordopen in new window and you'll be able to login to the smtp via that app password only.

Test the setup

echo "Here add your email body" | mail -s "Here specify your email subject" your_recepient_email@yourdomain.com
Last Updated: