2

I want to be able to run a script after a certain duration has elapsed. I also want to be able to cancel it and reschedule it, i.e. increase the duration on-the-fly.

I was thinking of somthing like this ->

stop_prev_instance.sh; sleep 60 && /etc/init.d/myscript reload

My problem is I need the stop_prev_instance.sh to only stop the previous run if it was sleeping, and not if the /etc/init.d/myscript reload command is running.

What would be the right way to solve this problem?

2

Maybe use lockfile (from procmail project) for such a "cancel-and-reload" script.

#!/bin/bash

SLEEP=$1
LOCKFILE="/tmp/reload.lock"
MYPID=$$
MYNAME=$(basename "$0")

lockfile "$LOCKFILE"
# kill all other scripts with the same name
KILLPIDS=$(pgrep "^${MYNAME:0:12}" | grep -v "^$MYPID\$")
kill $KILLPIDS 2>/dev/null
rm -f "$LOCKFILE"

sleep "$SLEEP"

lockfile "$LOCKFILE"
/etc/init.d/myscript reload
rm -f "$LOCKFILE"

At most one script will be executing between the lockfile and the rm commands.

Note, the reload-lock file should be better placed somewhere where only one user has write permissions (not /tmp!).

  • Thank you for your answer. I'm not a bash guy so I maybe wrong, but this solution doesn't seem to satisfy my requirement to stop all previous instances of the script. – user3490458 May 8 '17 at 14:55
  • All I had in my stop_prev_instance.sh was something like a kill -INT pgrep myscript``, and it wasn't working as mentioned in the question. :( Could you please update your answer with a working implementation of such a script (or perhaps add it directly to above script)? – user3490458 May 9 '17 at 6:00
  • @user3490458 I've added some code to kill the other previous scripts, hopefully it's good enough. – rudimeier May 9 '17 at 7:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.