简体   繁体   中英

Run Python Script on CentOS as a Background Task

I rented a CentOS 7 Server for my python scripts. I created a python script that connects my telegram account and forwards messages to targets. I used telethon to do this. When I connect to server via ssh, I can run script. When I logged out, my script is not working.

I used nohup and & but still can't run script until reboot or shutdown. After logout with nohup, my script working for a while but shutting down again.

What are the points that I miss?

Background processes are related to the user session, once you disconnect that session ends and such processes are terminated. To solve your problem you need to create a service which runs independently. In particular you need to first create a service configuration file:

[Unit]
Description=My Python program
After=network.target
StartLimitIntervalSec=0

[Service]
Type=simple
Restart=always
RestartSec=1
User=centos
ExecStart=<command to start your program>

[Install]
WantedBy=multi-user.target

Where is the command you use to execute your program.

This file needs to be saved in /etc/systemd/system/<my_service>.service where <my_service> is a name of your choice.

To make the program started when system reboot:

sudo systemctl enable <my_service>.service

To start manually the program:

sudo systemctl start <my_service>.service

This should fix your issue

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM