Skip to content

Instantly share code, notes, and snippets.

@jonashaag
Created June 12, 2023 13:53
Show Gist options
  • Save jonashaag/bccc32a418399810de9a0546db81b8c0 to your computer and use it in GitHub Desktop.
Save jonashaag/bccc32a418399810de9a0546db81b8c0 to your computer and use it in GitHub Desktop.
Bash regularly restart a program
#!/bin/bash
set -euo pipefail
if [ $# -lt 2 ]; then
echo "Usage: $0 SCHEDULE PROG [ARGS]..." >&2
echo "SCHEDULE is used in 'date -d <SCHEDULE>'." >&2
echo "Example: $0 '1 hour' myprog --arg" >&2
exit 1
fi
function stop_prog() {
if [ -n "${prog_pid:-}" ]; then
echo -n "Stopping PID $prog_pid... " >&2
kill $prog_pid
wait $prog_pid
echo "done" >&2
fi
}
trap "echo Received exit signal >&2 && stop_prog" EXIT
restart_schedule="$1"
shift
while true; do
# Start program in background
"$@" &
prog_pid=$!
# Wait for next restart
next_restart="$(date -d "$restart_schedule")"
next_restart_unix="$(date -d "$next_restart" "+%s")"
echo "Started $1 as PID $prog_pid. Next restart: $next_restart" >&2
while true; do
sleep 10
if [ "$(date "+%s")" -gt $next_restart_unix ]; then
stop_prog
break
fi
done
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment