Created
February 7, 2014 14:59
-
-
Save halvener/8864257 to your computer and use it in GitHub Desktop.
A template for setting up a daemon that can be interrupted nicely.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
shopt -s -o nounset | |
################################################## | |
# Define Operating Variables | |
# DAEMON Indicating whether to continue the loop or not | |
# SLEEP_TIME Defines how long to sleep (in seconds) between executions | |
DAEMON=true | |
SLEEP_TIME=300 | |
################################################## | |
# Trap SIGUSR2 to allow the daemon to cleanly exit. | |
# By issuing kill -SIGUSR2 <pid> OR pkill -SIGUSR2 daemon.bash | |
# we can allow the program to finish what it's doing instead | |
# of just stoping it. | |
trap "DAEMON=false" SIGUSR2 | |
################################################## | |
# Run our daemon | |
while [ $DAEMON == "true" ]; do | |
# Re-initialize the SLEEP_PID | |
SLEEP_PID="" | |
# This is the code that we want to periodically run | |
<run> | |
<code> | |
<here> | |
# Sleep | |
sleep <time> & | |
SLEEP_PID=$! | |
# Trap SIGUSR1 to terminate the sleep early | |
# Then wait for the sleep to end. | |
# When one of these happens, the loop will continue | |
trap "kill $SLEEP_PID" SIGUSR1 | |
wait $SLEEP_PID | |
trap "" SIGUSR1 | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment