Linux下如何创建随机启动任务

方法一:rc.local

  • 最简单且比较常用的方法是在/etc/rc.local(/etc/rc.d/rc.local)文件中添加脚本,该脚本会在启动时被调用,如此以来就能实现随机启动的目的

方法二:systemctl

  • systemctl是linux操作系统的系统控制器,他可以管理系统的各种服务,其实方法一的本质是在systemctl中注册了一个rc-local.service的服务,这个服务中会调用/etc/rc.local中的脚本,然后这个服务会随机启动

  • 如何注册一个systemctl服务?只要在/etc/systemd/system目录下创建一个xxx.service的文件即可,我们看看rc-local.service是如何编写的

    #  SPDX-License-Identifier: LGPL-2.1+
    #
    #  This file is part of systemd.
    #
    #  systemd is free software; you can redistribute it and/or modify it
    #  under the terms of the GNU Lesser General Public License as published by
    #  the Free Software Foundation; either version 2.1 of the License, or
    #  (at your option) any later version.
    
    # This unit gets pulled automatically into multi-user.target by
    # systemd-rc-local-generator if /etc/rc.d/rc.local is executable.
    [Unit]
    Description=/etc/rc.d/rc.local Compatibility
    Documentation=man:systemd-rc-local-generator(8)
    ConditionFileIsExecutable=/etc/rc.d/rc.local
    After=network.target
    
    [Service]
    Type=forking
    ExecStart=/etc/rc.d/rc.local start
    TimeoutStartSec=0
    TimeoutStopSec=30
    RemainAfterExit=yes
    GuessMainPID=no
    
  • 最基本最简单的service文件
    [Service]
    Type=forking
    ExecStart=/...
    [Install]
    WantedBy=multi-user.target
    
  • 设置好了service文件后,需要随机启动还需要执行一行命令
    ~:$ systemctl enable xxx
    

Leave a Reply