Thursday, 8 August 2019

Crontab example – every 5 minutes

Crontab example

Recently I installed memcached server on CentOS operating system to use as a caching mechanism for my VBulletin forum. To make sure that it’s running always, I wrote a shell script to check the process status and restart if it’s not running. Now to make sure this script executes at a specific interval, I used crontab.

Crontab Example Shell Script

The shell script is extendable and you can write a similar script to restart any service or process in unix systems.
Here is the shell script to auto restart service that I am using in my crontab example.
memcached_restart.sh

#!/bin/bash
ps -eaf | grep 11211 | grep memcached
# if not found - equals to 1, start it
if [ $? -eq 1 ]
then
/usr/local/bin/memcached -d -u nobody -p 11211 -U 11211 -l 127.0.0.1
else
echo "eq 0 - memcached running - do nothing"
fi
The main command in this script is to check the process, use “ps” command with grep to make sure that it returns only the desired service and returns nothing if the service is not running.
Once you have come up with the command to use, then only thing is to issue a start command to run the service.
Test the script to make sure it’s working as expected before setting it to run at regular intervals using crontab.
crontab example shell script

Crontab every 5 minutes example

Once you are done with the script, you need to set up a cron job to execute this script at regular interval.
I used below entry to run this script every 5 minutes.

*/5 * * * * /Users/pankaj/Downloads/memcached_restart.sh > /Users/pankaj/Downloads/memcache_restart.log 2>&1
crontab every 5 minutes

Crontab Error – command not found

Note that crontab doesn’t consider environment variables such as PATH, so you have to always provide absolute path for any program or directory location. If you are getting “command not found” error while running a command in a crontab shell script and it runs fine if you execute yourself, then using the relative path will be the problem.

0 comments:

Post a Comment