|
| 1 | +# systemd |
| 2 | + |
| 3 | +In order to have a command or program run when the Pi boots, you can add it as a service. Once this is done, you can start/stop enable/disable from the linux prompt. |
| 4 | + |
| 5 | +## Creating a service |
| 6 | + |
| 7 | +On your Pi, create a .service file for your service, for example: |
| 8 | + |
| 9 | +myscript.service |
| 10 | + |
| 11 | +```[Unit] |
| 12 | +Description=My service |
| 13 | +After=network.target |
| 14 | +
|
| 15 | +[Service] |
| 16 | +ExecStart=/usr/bin/python3 -u main.py |
| 17 | +WorkingDirectory=/home/pi/myscript |
| 18 | +StandardOutput=inherit |
| 19 | +StandardError=inherit |
| 20 | +Restart=always |
| 21 | +User=pi |
| 22 | +
|
| 23 | +[Install] |
| 24 | +WantedBy=multi-user.target |
| 25 | +``` |
| 26 | +So in this instance, the service would run Python 3 from our working directory `/home/pi/myscript` which contains our python program to run `myscript.py`. But you are not limited to Python programs: simply change the ExecStart line to be the command to start any program/script that you want running from booting. |
| 27 | + |
| 28 | +Copy this file into `/lib/systemd/system` as root, for example: |
| 29 | +``` |
| 30 | +sudo cp myscript.service /lib/systemd/system/myscript.service |
| 31 | +``` |
| 32 | + |
| 33 | +Once this has been copied, you can attempt to start the service using the following command: |
| 34 | +``` |
| 35 | +sudo systemctl start myscript.service |
| 36 | +``` |
| 37 | + |
| 38 | +Stop it using following command: |
| 39 | +``` |
| 40 | +sudo systemctl stop myscript.service |
| 41 | +``` |
| 42 | +When you are happy that this starts and stops your app, you can have it start automatically on reboot by using this command: |
| 43 | +``` |
| 44 | +sudo systemctl enable myscript.service |
| 45 | +``` |
| 46 | + |
| 47 | +The `systemctl` command can also be used to restart the service or disable it from boot up! |
| 48 | + |
| 49 | +Some things to be aware of: |
| 50 | ++ The order in which things are started is based on their dependencies — this particular script should start fairly late in the boot process, after a network is available (see the After section). |
| 51 | ++ You can configure different dependencies and orders based on your requirements. |
| 52 | + |
| 53 | + |
| 54 | +You can get more information from: |
| 55 | +``` man systemctl``` |
| 56 | +or here: https://fedoramagazine.org/what-is-an-init-system/ |
| 57 | + |
| 58 | +Also be sure to reference absolute file names rather than doing so relative to your home folder, for example use `/home/pi/myscript.py` rather than `myscript.py`. |
0 commit comments