Hey, a video about the jobs command. Reminds me of a docker container I once had that, for some reason, sometimes wouldn’t exit and keep running forever.
This container was launched by a cronjob every minute, with --rm
and the exact same name every time. Which is an issue for docker, it refuses to start a container if a container with the same name is already running.
Never found out why it sometimes refused to stop, other stuff to do and whatnot.
So what did I do to handle the situation?
Wrote this here script and had the docker image run that instead:
#!/usr/bin/env bash
sleep 20 &
pid=$!
# SLEEP_TIME is an env variable.
start_time="$(date -u +%s)"
while [[ "$(jobs -pr)" == *"${pid}"* ]];
do
end_time="$(date -u +%s)"
elapsed="$((end_time-start_time))"
if [[ "${elapsed}" -gt "${SLEEP_TIME}" ]]; then
kill -9 "${pid}"
exit 1
fi
done
exit 0
The “sleep 20 &” is whatever your actual script needs to be. Replace as needed.
The script also uses an environment variable(hey, environment variables and passing them along to commands, maybe idea for a next video).
The basic idea is: the command is allowed to run a certain length of time but if it exceeds that amount of time, kill it. If it exits normally, that’s just fine.
Thought I’d share.
People might argue this is the equivalent of shooting a canon at a bee, but let me tell you: that bee is dead!