Skip to content

Instantly share code, notes, and snippets.

@kamilbednarz
Created February 14, 2018 12:18
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kamilbednarz/5ea6398af2a7537aa8feb5a63f3acf2f to your computer and use it in GitHub Desktop.
Save kamilbednarz/5ea6398af2a7537aa8feb5a63f3acf2f to your computer and use it in GitHub Desktop.
Stop sidekiq, but first wait until it finishes all the running jobs
#!/bin/bash
RETRY_FREQUENCY=5
MAX_TRIES=100
PIDFILE=/var/www/app/current/tmp/pids/sidekiq.pid
# Helper function for printing logs with timestamp
echo_time() {
date +"[%H:%M:%S] [Sidekiq-smart-restart] $*"
}
if [ ! -f $PIDFILE ]; then
echo_time 'PID file not found'
exit 1
fi
PID=`cat $PIDFILE`
ps --pid $PID 2>&1 > /dev/null
if [ $? -eq 1 ]; then
echo_time "Sidekiq process does not exist"
exit 1
fi
# First, let's make sure that sidekiq does not pick up more jobs
echo_time "TSTP signal - Ask sidekiq to not pick up more jobs"
kill -TSTP $PID 2>&1 > /dev/null
# Now, let's wait until it finishes all the jobs and then send a TERM signal to it
for ((i=1; i<=$MAX_TRIES; i++))
do
IS_SIDEKIQ_DONE=$(ps -f --pid $PID | grep -v PID | grep -E "\[0 of [0-9]+ busy\]" > /dev/null)$?
if [ $IS_SIDEKIQ_DONE -eq 0 ]; then
echo_time "Sidekiq is done with its jobs"
break
else
echo_time "Sidekiq is still busy"
sleep $RETRY_FREQUENCY
fi
if [ $i -eq $MAX_TRIES ]; then
echo_time "Can't wait any longer, maximum number of retries reached"
fi
done
echo_time "TERM signal - Shutting down sidekiq"
kill -TERM $PID 2>&1 > /dev/null
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment