Created
November 14, 2021 23:32
-
-
Save frafra/5ae0f0c070f9574e72ffe42f400d176f to your computer and use it in GitHub Desktop.
Run a service in a specific time range using systemd
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 | |
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 |
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 | |
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