Skip to content

Instantly share code, notes, and snippets.

@frafra
Created November 14, 2021 23:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save frafra/5ae0f0c070f9574e72ffe42f400d176f to your computer and use it in GitHub Desktop.
Save frafra/5ae0f0c070f9574e72ffe42f400d176f to your computer and use it in GitHub Desktop.
Run a service in a specific time range using systemd
#!/bin/bash
for unit in test_python_stop.service test_python_{start,stop}.timer
do
systemctl --user stop $unit
systemctl --user disable $unit
done
systemctl --user stop test_python.service
rm -f \
~/.config/systemd/user/test_python.service \
~/.config/systemd/user/test_python_stop.service \
~/.config/systemd/user/test_python_start.timer \
~/.config/systemd/user/test_python_stop.timer \
~/bin/test_python.py
systemctl --user daemon-reload
#!/bin/bash
mkdir -p ~/bin
cat << EOF > ~/bin/test_python.py
#!/usr/bin/env python3
import time
counter = 0
while True:
counter += 1
print(counter)
time.sleep(5)
EOF
chmod +x ~/bin/test_python.py
cat << EOF > ~/.config/systemd/user/test_python.service
[Unit]
Description=Test Python
[Service]
ExecStart=/usr/bin/python3 -u %h/bin/test_python.py
[Install]
WantedBy=default.target
EOF
cat << EOF > ~/.config/systemd/user/test_python_start.timer
[Unit]
Description=Test Python - Start timer
[Timer]
Unit=test_python.service
Persistent=true
OnBootSec=60s
OnCalendar=*-*-* 10:00:00
[Install]
WantedBy=timers.target
EOF
cat << EOF > ~/.config/systemd/user/test_python_stop.service
[Unit]
Description=Test Python - Stop service
Conflicts=test_python.service
[Service]
ExecStart=echo
[Install]
WantedBy=default.target
EOF
cat << EOF > ~/.config/systemd/user/test_python_stop.timer
[Unit]
Description=Test Python - Stop timer
Conflicts=test_python.service
[Timer]
Unit=test_python_stop.service
OnCalendar=*-*-* 22:00:00
[Install]
WantedBy=timers.target
EOF
systemctl --user daemon-reload
for unit in test_python_stop.service test_python_{start,stop}.timer
do
systemctl --user enable $unit
done
systemctl --user restart timers.target
systemctl --user list-timers --all
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment