Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Schedule cron entries to run script only when not already running

I have one shell script in crontab which is executing jar file. Jar file is moving files from one server to another server. In peak hours it is taking more then 10 minutes(more then crontab entries).

How can I make sure that cron job will not execute process until last one is not completed ?

like image 871
ajkush Avatar asked Dec 14 '22 15:12

ajkush


2 Answers

An easy way would be to have your Cron start a bashfile that checks if such a process exist.

cron:

 */10 * * * * /path/to/bashscript.sh

(Make sure it has the correct user and is executable)

The pgrep command looks for a process with a the given name, and returns the processID when such a process is found.

#!/bin/bash
# bashscript.sh    

pID=$(pgrep -n "yourjarfile") 

# Check if jarfile is running
if $pID > /dev/null
then       
    #log something to syslog 
    logger  $pID "already running. not restarting." 
else
    # start jar file 
    /usr/bin/java -jar /path/to/yourjarfile.jar
fi

--EDIT--

Inspired by F. Hauri's answer (which works fine btw), I came up with a shorter version :

 */10 * * * *  pgrep -n "yourjarfile." || /usr/bin/java -jar /path/to/yourjarfile.jar
like image 85
Alex Avatar answered Jan 08 '23 02:01

Alex


You can use a poor man's lockfile directly in the cron entry, something such as:

* * * * * LOCKFILE=whatever; [ ! -f $LOCKFILE ] && (touch $LOCKFILE && /path/to/java javaargs ; rm $LOCKFILE)

like image 41
ggiroux Avatar answered Jan 08 '23 00:01

ggiroux