这是我想要的一个python示例。将@
在该服务名让你开始数处理:
$ cat /etc/systemd/system/my-worker@.service
[Unit]
Description=manages my worker service, instance %i
After=multi-user.target
[Service]
PermissionsStartOnly=true
Type=idle
User=root
ExecStart=/usr/local/virtualenvs/bin/python /path/to/my/script.py
Restart=always
TimeoutStartSec=10
RestartSec=10
各种调用方法
启用各种计数,例如:
然后确保重新加载:
sudo systemctl daemon-reload
现在,您可以通过多种方式启动/停止:
开始1:
sudo systemctl start my-worker@2.service
开始多个:
sudo systemctl start my-worker@{1..2}
停止多个:
sudo systemctl stop my-worker@{1..2}
检查状态:
sudo systemctl status my-worker@1
更新:要将实例作为一项服务进行管理,您可以执行以下操作:
/etc/systemd/system/some-worker@.service:
[Unit]
Description=manage worker instances as a service, instance %i
Requires=some-worker.service
Before=some-worker.service
BindsTo=some-worker.service
[Service]
PermissionsStartOnly=true
Type=idle
User=root
#EnvironmentFile=/etc/profile.d/optional_envvars.sh
ExecStart=/usr/local/virtualenvs/bin/python /path/to/my/script.py
TimeoutStartSec=10
RestartSec=10
[Install]
WantedBy=some-worker.service
/usr/bin/some-worker-start.sh:
#!/bin/bash
systemctl start some-worker@{1..10}
/etc/systemd/system/some-worker.service:
[Unit]
Description=manages some worker instances as a service, instance
[Service]
Type=oneshot
ExecStart=/usr/bin/sh /usr/bin/some-worker-start.sh
RemainAfterExit=yes
[Install]
WantedBy=multi-user.target
现在,您可以使用 sudo systemctl some-worker (start|restart|stop)
这是您的一些样板script.py
:
#!/usr/bin/env python
import logging
def worker_loop():
shutdown = False
while True:
try:
if shutdown:
break
# Your execution logic here.
# Common logic - i.e. consume from a queue, perform some work, ack message
print("hello world")
except (IOError, KeyboardInterrupt):
shutdown = True
logging.info("shutdown received - processing will halt when jobs complete")
except Exception as e:
logging.exception("unhandled exception on shutdown. {}".format(e))
if __name__ == '__main__':
worker_loop()