Skip to content

Instantly share code, notes, and snippets.

@shawngmc
Last active September 25, 2025 19:42
Show Gist options
  • Select an option

  • Save shawngmc/6053d0e6cbaf881852bb4d919d7342d6 to your computer and use it in GitHub Desktop.

Select an option

Save shawngmc/6053d0e6cbaf881852bb4d919d7342d6 to your computer and use it in GitHub Desktop.
Systemd Cron Task Example w/Email
# Timer/Service Impl
SERVICE_NAME=""
SNS_TOPIC=""
# Script-specific
#!/bin/bash
chmod 700 script.sh
# Ensure config has been set up
ENV_FILE="$(dirname $0)/env"
if [ ! -f "${ENV_FILE}" ]; then
echo "File ${ENV_FILE} does not exist - please create before installing by copying from env.template and filling out!"
exit 1
else
echo "File ${ENV_FILE} exists."
fi
source "${ENV_FILE}"
# Update unit path and name
cp "$(dirname $0)/script.service" "$(dirname $0)/${SERVICE_NAME}.service"
cp "$(dirname $0)/script.timer" "$(dirname $0)/${SERVICE_NAME}.timer"
sed -i "s|^ExecStart=.*|ExecStart=/bin/bash $(dirname $0)/script.sh|" "$(dirname $0)/${SERVICE_NAME}.service"
sed -i "s|SERVICE_NAME|${SERVICE_NAME}|g" "$(dirname $0)/${SERVICE_NAME}.service"
sed -i "s|SERVICE_NAME|${SERVICE_NAME}|g" "$(dirname $0)/${SERVICE_NAME}.timer"
# Apply units
sudo mv "$(dirname $0)/${SERVICE_NAME}.service" "/etc/systemd/system/${SERVICE_NAME}.service"
sudo chmod 644 "/etc/systemd/system/${SERVICE_NAME}.service"
sudo mv "$(dirname $0)/${SERVICE_NAME}.timer" "/etc/systemd/system/${SERVICE_NAME}.timer"
sudo chmod 644 "/etc/systemd/system/${SERVICE_NAME}.timer"
sudo systemctl daemon-reload
sudo systemctl enable "${SERVICE_NAME}.timer"
[Unit]
Description=Execute a bash script for SERVICE_NAME
[Service]
Type=oneshot
ExecStart=
#!/bin/bash
source "$(dirname $0)/env"
notify() {
# Send notification
aws sns publish --topic-arn "${SNS_TOPIC}" --message "$1"
}
handle_error() {
notify "ERROR: ${SERVICE_NAME} failed on line ${LINENO}!"
exit 1
}
trap handle_error ERR
# Example: 50/50 Success/Failure
random_byte=$(od -An -N1 -t u1 /dev/urandom)
if (( random_byte % 2 == 0 )); then
result="True - Worked"
else
result="ERROR - False - Failed"
exit 1
fi
notify "OK: ${SERVICE_NAME} completed OK!"
[Unit]
Description=Start the matching Systemd SERVICE_NAME.service on schedule
[Timer]
OnCalendar="Mon,Wed,Fri 1:0"
Persistent=true
[Install]
WantedBy=timers.target
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment