CentOS에서 특정 시간에 Python 스크립트를 서비스로 시작/중지하는 방법은 무엇입니까?

CentOS에서 특정 시간에 Python 스크립트를 서비스로 시작/중지하는 방법은 무엇입니까?

웹 서비스에서 온라인으로 일부 주식 데이터를 긁어내는 CentOS 7을 실행하는 VPS에 Python 스크립트를 넣으려고 합니다. 내가 원하는 것은 이 스크립트를 특정 시간에 시작/중지하는 운영 체제 서비스로 설정하는 것입니다.

어떻게 해야 합니까?

편집 : 결과는 다음과 같습니다systemctl status python-script

   Loaded: loaded (/etc/systemd/system/python-script.service; enabled; vendor preset: disabled)
   Active: failed (Result: exit-code) since Sat 2020-05-16 01:11:50 +0430; 15h ago
 Main PID: 854 (code=exited, status=1/FAILURE)

May 16 01:11:43 boiga.server1.more.com systemd[1]: Started Python Script Serv...
May 16 01:11:50 boiga.server1.more.com python3[854]: Traceback (most recent c...
May 16 01:11:50 boiga.server1.more.com python3[854]: File "/root/script.py", ...
May 16 01:11:50 boiga.server1.more.com python3[854]: await (websocketConnect())
May 16 01:11:50 boiga.server1.more.com python3[854]: NameError: name 'await' ...
May 16 01:11:50 boiga.server1.more.com systemd[1]: python-script.service: mai...
May 16 01:11:50 boiga.server1.more.com systemd[1]: Unit python-script.service...
May 16 01:11:50 boiga.server1.more.com systemd[1]: python-script.service failed.
Hint: Some lines were ellipsized, use -l to show in full.

답변1

/etc/systemd/system/python-script.service다음 예와 같이 서비스 파일을 생성하여 이 Python 스크립트를 실행하는 서비스를 생성할 수 있습니다 .

[Unit]
Description=Python Script Service
After=network.target

[Service]
Type=simple
User=root
ExecStart=/usr/bin/python3 /root/script.py
Restart=on-abort


[Install]
WantedBy=multi-user.target

그런 다음 실행 systemctl daemon-reload하여 systemd를 다시 로드하고 systemctl enable python-script서비스를 활성화합니다.

서비스를 실행하면 다음과 같은 결과가 나타납니다.

systemctl status python-script
● python-script.service - Python Script Service
   Loaded: loaded (/etc/systemd/system/python-script.service; enabled; vendor preset: disabled)
   Active: inactive (dead) since Wed 2020-05-13 23:10:30 CEST; 2s ago
  Process: 27405 ExecStart=/usr/bin/python3 /root/script.py (code=exited, status=0/SUCCESS)
 Main PID: 27405 (code=exited, status=0/SUCCESS)

May 13 23:10:30 server1 systemd[1]: Started Python Script Service.
May 13 23:10:30 server1 python3[27405]: Hello World!

예약된 서비스의 시작/중지와 관련하여 crontab을 사용하여 다음을 달성할 수 있습니다.

관련 정보