To automate tasks or create some monitoring job we can use the older and efficient tool the “CronJob”.

For our example, I’ve created a simple script to detect the cache memory and clean it if raise to a condition then send a notification by mail.

Library used:

  • exim4 (mail server) or ssmtp (mail server). Both uses the same “mail” command.

Script:

# grab the buff/cache memory
mem="$(free -m | grep 'Mem:' | awk '{print $6}')"

if  (( $mem > 350 ))
then
echo 'wooo is more than 250M'
echo 3 | sudo tee /proc/sys/vm/drop_caches
echo 'cache dropped'
echo "Memory buff/cache cleaned last value:" $mem | mail -s "cache_memory" target_mail@local.com
else
echo 'be cool man, memory lower'
fi

script path: /user/Documents/script/memory

Crontab description:

* * * * * /user/Documents/script/memory
- - - - -
| | | | |
| | | | ----- Day of week (0 - 7) (Sunday=0 or 7)
| | | ------- Month (1 - 12)
| | --------- Day of month (1 - 31)
| ----------- Hour (0 - 23)
------------- Minute (0 - 59)

Above it shows how works the interpretation of the line added to make the job works by cron.

To start to add our job issue the command below:

$ crontab -e

Set the schedule of the job plus the path to the script.

0 * * * * /user/Documents/scripts/memory #Execute script every hour

*/5 * * * * /user/Documents/scripts/memory #Execute script each 5 min

Save and exit, after check the job set using the command below:

$ crontab -l

to check that our cronjobs are correctly working, we can have a look:

$ journalctl -b 0 _SYSTEMD_UNIT=cron.service | grep "(/home/user/scripts/mem)"

or

$ sudo journalctl -u cron.service | grep "scripts"

From the above commands, I pointed the folder where I save my scripts, so on my case I filtered it as “scripts” so I can grab the output where the cronjob executes the script from that folder.