Run script on startup

The restart can be automated, no interaction required.

I tried with this super useful program.

$ cat/home/xabbu/test22/main.py
import time

while (True):
        print ("test")
        time.sleep(5)

$ cat test.service
[Unit]
Description=Start scripts
After=network.target
Requires=network-online.target

[Service]
Type=forking
ExecStart=/usr/bin/tmux new-session -d -s 0 'cd /home/xabbu/test22 && python main.py'

[Install]
WantedBy=multi-user.target

$ systemctl status test.service
● test.service - Start scripts
     Loaded: loaded (/etc/systemd/system/test.service; disabled; vendor preset: disabled)
     Active: active (running) since Sat 2022-03-26 19:21:54 CET; 5min ago
    Process: 19502 ExecStart=/usr/bin/tmux new-session -d -s 0 cd /home/xabbu/test22 && python main.py (code=exited, status=0/SUCCESS)
   Main PID: 19504 (tmux: server)
      Tasks: 2 (limit: 2349)
     Memory: 4.6M
        CPU: 48ms
     CGroup: /system.slice/test.service
             ├─19504 /usr/bin/tmux new-session -d -s 0 "cd /home/xabbu/test22 && python main.py"
             └─19505 python main.py

Mar 26 19:21:54 arch.vir systemd[1]: Starting Start scripts...
Mar 26 19:21:54 arch.vir systemd[1]: Started Start scripts.

Work with my little python script. Since it will run as root, are you sure all permissions are correct? Did you started it before as root or as your normal user.

1 Like

What do you mean by this? All im doing is editing the file, running sudo systemctl daemon-reload, rebooting my pi and then trying to attach to the session with tmux a -t 0 but it says no sessions

the default user for systemd system services is root. If tmux is started by root, you need to be root to attach to it.

If you want that processes of a service are run by a specif user and the application can do this by itself, you need to use the User=myuser directive in the service section.

Depending on what this application does, running as root might be a problem.

2 Likes

I see what you mean; I just tried to attach to the tmux in root but still no luck. I will add User=pi (the user) in the service

Something worked!! tmux a -t 0 attachs to my session :open_mouth:
Finally :slight_smile:

1 Like

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.