Jump to content

Autostart Python Script on Raspberry Pi to run 24/7


Recommended Posts

Hello, I want to run a python script 24/7. I am using systemd service and it looks like this:


[Unit]
Description= start code
After=multi-user.target

[Service]
Type=simple
ExecStart= /usr/bin/python3 /home/pi3/code1.py
Restart=on-abort


[Install]
WantedBy=multi-user.target

When I enabled the systemd service it was running without error. but after few hours it stopped. I got the following error.

● codestart.service - start code
     Loaded: loaded (/lib/systemd/system/codestart.service; enabled; vendor preset: enabled)
     Active: failed (Result: exit-code) since Tue 2022-06-07 16:13:15 CEST; 20h ago
    Process: 859 ExecStart=/usr/bin/python3 /home/pi3/code1.py (code=exited, status=1/FAILURE)
   Main PID: 859 (code=exited, status=1/FAILURE)
        CPU: 1.086s

Jun 07 16:13:15 raspberrypi python3[859]:   File "/home/pi3/code1.py", line 54, in main
Jun 07 16:13:15 raspberrypi python3[859]:     ipcon.connect(HOST, PORT)
Jun 07 16:13:15 raspberrypi python3[859]:   File "/usr/local/lib/python3.9/dist-packages/tinkerforge/ip_connection.py", lin>
Jun 07 16:13:15 raspberrypi python3[859]:     self.connect_unlocked(False)
Jun 07 16:13:15 raspberrypi python3[859]:   File "/usr/local/lib/python3.9/dist-packages/tinkerforge/ip_connection.py", lin>
Jun 07 16:13:15 raspberrypi python3[859]:     tmp.connect((self.host, self.port))
Jun 07 16:13:15 raspberrypi python3[859]: OSError: [Errno 101] Network is unreachable
Jun 07 16:13:15 raspberrypi systemd[1]: codestart.service: Main process exited, code=exited, status=1/FAILURE
Jun 07 16:13:15 raspberrypi systemd[1]: codestart.service: Failed with result 'exit-code'.
Jun 07 16:13:15 raspberrypi systemd[1]: codestart.service: Consumed 1.086s CPU time.
~

Can you please suggest what should I do to restart the code in case of network failure? Thanks

Link to comment
Share on other sites

The simplest way is to use

Restart=always
RestartSec=5

instead of

Restart=on-abort

in the systemd service file.

The restart on-abort doesn't trigger in the case you are running into here.

The default restart delay is 100 milliseconds. That might be a bit fast. That's why i suggest 5 second restart delay.

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

×
×
  • Create New...