Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Simple daily cron job as Kubernetes container image. See http://blog.schlomo.schapiro.org/2017/06/using-kubernetes-with-multiple.html for details.
Copyright 2017 Schlomo Schapiro / Zalando SE
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#!/bin/bash
# RUNAT could be "03:33" "next day 03:33" or "next hour" or "2 hours", everything that date -d understands
# if the sleep time is negative then don't wait as we obviously already missed our time
# please try out new RUNAT values with (GNU coreutils) date -d before deploying!
# You will probably have more configuration variables here, just follow the same schema
RUNAT=${RUNAT:-1 minute}
set -ue -o pipefail
echo MAINTENANCE CONTAINER
echo ARGS: RUNAT=$RUNAT
function wait_for_maintenance_time {
sleep_time=$(( $(date -d "$RUNAT" +%s ; echo - ; date +%s) ))
if (( sleep_time < 0 )) ; then
sleep_time=$(( 24*60*60 + sleep_time )) # wait till next day same time
fi
if (( sleep_time > 0 )) ; then
echo "Waiting $sleep_time seconds till $RUNAT before starting maintenance"
sleep $sleep_time
else
echo "Not waiting $sleep_time seconds"
fi
}
while true ; do
wait_for_maintenance_time
echo "STARTING MAINTENANCE CYCLE AT $(date)"
# do some maintenance, e.g. backup data or purge old stuff
echo "Waiting 60 seconds as buffer"
sleep 60 # minimum wait between cycles and to make sure that specifying a time without seconds works
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment