[ systemctl任务管理使用 ]


systemctl任务管理使用(守护进程运行...)

test_example.py文件

import time
import logging

# 这个文件夹需要提前存在
logging.basicConfig(filename='/home/chf/python_obj/python_test/systemctl-test/test_example.log', level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

while True:
    try:
        # 运行您的应用程序逻辑
        logging.info('Running application logic...')
        time.sleep(10)  # 为了演示目的,在此处添加一个延迟
    except Exception as e:
        logging.info(f"Exception occurred: {str(e)}")
        # 在这里可以记录日志或采取其他异常处理措施

test_example.service

[Unit]
Description=Test Example Service
After=network.target

[Service]
Type=simple
Restart=always
RestartSec=5
ExecStart=/home/chf/anaconda3/envs/test/bin/python /home/chf/python_obj/python_test/systemctl-test/test_example.py
WorkingDirectory=/home/chf/python_obj/python_test/systemctl-test
StandardOutput=journal
StandardError=journal
User=chf

[Install]
WantedBy=multi-user.target

注意事项ExecStart是python test_example.py同理, WorkingDirectory是py文件的文件夹, User是用户, RestartSec异常重启5s一次

启动

sudo cp example.service /etc/systemd/system/
sudo systemctl daemon-reload
sudo systemctl start example

基本使用

# 启动,重启
sudo systemctl daemon-reload
sudo systemctl start example
sudo systemctl restart example

# 查看状态
sudo systemctl status example

# 开机自启
sudo systemctl enable example

# 删除
sudo systemctl stop example

sudo rm /etc/systemd/system/example.service