Autoinstall script for systemd timer and associated service
The following script will install a systemd .timer file and the associated .service file into /etc/systemd/system/ and enable the timer (i.e. start on boot) and start the timer immediately.
install_systemd_timer.sh
#!/bin/bash
# This script installs and enables/starts a systemd timer
# It also installs the service file that is run by the given timer
export NAME=MyService
cat >/etc/systemd/system/${NAME}.service <<EOF
# ADD SYSTEMD SERVICE FILE CONTENT HERE
EOF
cat >/etc/systemd/system/${NAME}.timer <<EOF
# ADD SYSTEMD TIMER FILE CONTENT HERE
EOF
# Enable and start service
systemctl enable --now ${NAME}.timerIn order to modify the script for your systemd service, replace MyService by the desired name of your service in
install_systemd_timer_set_name.sh
export NAME=MyServiceinsert the content of your .service file at
install_systemd_timer_service_placeholder.sh
# ADD SYSTEMD SERVICE FILE CONTENT HEREand insert the content of your .timer file at
install_systemd_timer_timer_placeholder.sh
# ADD SYSTEMD TIMER FILE CONTENT HEREFull example
The following complete example installs a systemd service named MyService that runs /usr/bin/python3 run.py every two hours:
install_systemd_timer_example.sh
#!/bin/bash
# This script installs and enables/starts a systemd timer
# It also installs the service file that is run by the given timer
export NAME=MyService
cat >/etc/systemd/system/${NAME}.service <<EOF
[Unit]
Description=${NAME}
[Service]
Type=oneshot
ExecStart=/usr/bin/python3 run.py
WorkingDirectory=/opt/myproject
EOF
cat >/etc/systemd/system/${NAME}.timer <<EOF
[Unit]
Description=${NAME} timer
[Timer]
OnCalendar=*-*-* 00,02,04,06,08,10,12,14,16,18,20,22:00:00
Persistent=true
[Install]
WantedBy=timers.target
EOF
# Enable and start service
systemctl enable --now ${NAME}.timerCheck out similar posts by category:
Systemd
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow