How to run a cron job in linux?

KARAN VERMA
2 min readJun 24, 2020

We often require to run a cron job on our staging or production environment.

This is how we can achieve this in linux:

1. Create a bash script

2. Schedule execution of the above script with crontab

Create a bash script

This is what the actual piece of work to be done.

Simply open any of your favourite editor and create the script. For a simple example add the lines as follows:

#!/bin/sh

a=`ps -ef | awk ‘/my-java-program.jar/{print $2}’`
b=`echo $a | head -1`
echo “killing job “

kill -9 $b

echo “starting job “
l=`date +”%d-%m-%y-%T”`
nohup java -jar /home/user/my-java-program.jar > /usr/logs/$l.log 2>&1 &

and save the file as myscript.sh in /home/user/ directory. (what this script is doing is not in the scope of this article)

Schedule execution of the above script with crontab

Make sure you are the sudoer user.

Simply edit the crontab using:

crontab -e

and add the following lines

*/30 * * * * /home/user/myscript.sh > /tmp/myscript.log

What this says is execute myscript.sh every 30 minutes.

You can change the schedule by changing the values for each start specified.

Where each star specifies the following:

  • 1st star: Minute (0–59)
  • 2nd star: Hours (0–23)
  • 3rd star: Day (0–31)
  • 4th star: Month (0–12 [12 == December])
  • 5th star: Day of the week(0–7 [7 or 0 == sunday])

Hope this article helps. Happy learning!!!

--

--