如何确保在systemd中启动服务之前存在延迟?

How to ensure that there is a delay before a service is started in systemd?

我所提供的服务依赖于Cassandra正常启动以及集群正常运行。

为了确保满足依存顺序,我有以下单位文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
[Unit]
Requires=cassandra.service
After=cassandra.service

[Service]
Environment=JAVA_HOME=/usr/java/jre
[email protected]@/webapps/bringup-app/bin/bringup
TimeoutStartSec=0
ExecStop=
[email protected]@/logs/bringup.pid
Restart=always

[Install]
WantedBy=multi-user.target

如何确保在启动应用程序之前,它会等待30秒? 目前,尽管它是在Cassandra之后启动的,但我注意到Cassandra集群尚未启动,因此在启动过程中,任何来自boostup-app尝试连接到Cassandra的尝试都失败了。

因此,我想增加一个延迟。 通过单位文件可以吗?


您可以在使用ExecStartPre的ExecStart之前运行sleep命令:

1
2
[Service]
ExecStartPre=/bin/sleep 30


您可以创建.timer systemd单位文件来控制.service单位文件的执行。

因此,例如,要在启动后等待1分钟再启动foo.service,请在同一目录中创建一个foo.timer文件,其内容如下:

1
2
[Timer]
OnBootSec=1min

重要的是,要禁用所有服务(这样它就不会在启动时启动)并启用计时器,所有这些才能正常工作(这要归功于用户部落):

1
2
systemctl disable foo.service
systemctl enable foo.timer

您可以在此处找到许多其他选项和所需的所有信息:https://wiki.archlinux.org/index.php/Systemd/Timers


与其编辑启动服务,不如将启动后延迟添加到它所依赖的服务上。像这样编辑cassandra.service

1
ExecStartPost=/bin/sleep 30

这样,增加的睡眠不应该减慢依赖于它的启动服务的重启(尽管会减慢其自身的启动速度,也许这是所希望的?)。


我认为对超级用户的此答案是更好的答案。
从https://superuser.com/a/573761/67952

"但是,由于您要求不使用"之前和之后"的方法,因此可以使用:

1
Type=idle

man systemd.service解释了

Behavior of idle is very similar to simple; however, actual execution of the service program is delayed until all active jobs are dispatched. This may be used to avoid interleaving of output of
shell services with the status output on the console. Note that this type is useful only to improve console output, it is not useful as a general unit ordering tool, and the effect of this
service type is subject to a 5s time-out, after which the service program is invoked anyway.
"


systemd执行此操作的方法是在以某种方式设置时使进程"回话",例如通过打开套接字或发送通知(或退出父脚本)。当然,这并不总是那么简单,尤其是对于第三方的东西:|

您也许可以做一些内联的事情

1
ExecStart=/bin/bash -c '/bin/start_cassandra &; do_bash_loop_waiting_for_it_to_come_up_here'

或执行相同操作的脚本。或者将do_bash_loop_waiting_for_it_to_come_up_here放在ExecStartPost中

或创建一个等待其启动的helper .service,这样,helper服务将依赖于cassandra,并等待其启动,然后您的其他进程将依赖于helper服务。

(可能还希望将TimeoutStartSec也从默认的90s增加)