| 1 | = Systemd service = |
| 2 | |
| 3 | Ref [https://medium.com/codex/setup-a-python-script-as-a-service-through-systemctl-systemd-f0cc55a42267 here] |
| 4 | |
| 5 | 1. Setup script to run as service called test.py |
| 6 | {{{ |
| 7 | #!python |
| 8 | import time |
| 9 | from datetime import datetime |
| 10 | while True: |
| 11 | with open("timestamp.txt", "a") as f: |
| 12 | f.write("The current timestamp is: " + str(datetime.now())) |
| 13 | f.close() |
| 14 | time.sleep(10) |
| 15 | }}} |
| 16 | |
| 17 | 2. nano /etc/systemd/system/test.service (name of the service which is test in this case) |
| 18 | {{{ |
| 19 | [Unit] |
| 20 | Description=My test service |
| 21 | After=multi-user.target |
| 22 | |
| 23 | [Service] |
| 24 | Type=simple |
| 25 | Restart=always |
| 26 | ExecStart=/usr/bin/python3 /home/<username>/test.py |
| 27 | |
| 28 | [Install] |
| 29 | WantedBy=multi-user.target |
| 30 | }}} |
| 31 | |
| 32 | 3. reload systemctl daemon |
| 33 | {{{ |
| 34 | #!sh |
| 35 | sudo systemctl daemon-reload |
| 36 | sudo systemctl enable test.service |
| 37 | sudo systemctl start test.service |
| 38 | sudo systemctl stop test.service |
| 39 | sudo systemctl restart test.service |
| 40 | sudo systemctl status test.service |
| 41 | }}} |
| 42 | |