cron job duplicate process by itself again and again

Dear expert,

I have a question concerning with cron job. this is my code sample:

00 7-20 * * * /home/usr/./  # is an executable file

The code runs perfectly. I leave the script on for 4 to 5 hours to see if the script can run without any issue. When I check the process after few hours I see 5 same process running at same time.

I've checked online that flock can "fix" this issue:

I've applied this:

00 7-20 * * * flock -n /home/usr/ -c /home/usr/./

somehow I got this error: /bin/bash: bad interpreter: Text file busy.

Is there away that I can reduce down the process that only one process is running when I activate my script through cron job? Thanks
Kinderly WadeprogrammerAsked:
Who is Participating?
Gerwin Jansen, EE MVEConnect With a Mentor Topic Advisor Commented:
I would not kill the script, it may be busy doing something. I would recommend to first check if the script is running already and if not, create the 'flag' file as suggested above. Then when the script finishes, remove the flag file. You could add some logging at the check part.

# check
if ! [ -r ${FLAGFILE} ]
touch ${FLAGFILE} 
# add logging here (optional)

# start
(your code here)

# finish
rm -f ${FLAGFILE} 

Open in new window

Just make sure no one cleans the flag file for some reason, you could store it elsewhere.
I beleive the problem is your time.

7-20 means running it every hour between 7 and 20.  This would mean a new process is started every hour between those hours.
Kinderly WadeprogrammerAuthor Commented:
Is there a way for me to configure that I want the script to start 7:00 am and stop at 8:pm? THanks
Zsolt PribuszConnect With a Mentor Commented:
You can do it with 2 crontab entry.
First you need to start your script, and then you need to kill it.
You can do this in many ways.
here is two sort example:

0 7 * * * /home/usr/
0 20 * * * pkill -f  #This will kill any process with in its command line 

Open in new window

If you want to be more specific, then modify your to store it's pid to some file:
Add this line to begining of your script
echo $$ > /tmp/

Open in new window

then you can kill process based on this file.
 0 20 * * * kill $(cat /tmp/

Open in new window

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.