首页 > 系统相关 >如何优雅的在Linux下开机自动重启脚本

如何优雅的在Linux下开机自动重启脚本

时间:2022-11-10 11:56:54浏览次数:75  
标签:脚本 Systemd 重启 优雅 sh Linux 开机 restart

1简介

经常碰到机器断电之后需要重启一大堆服务,为了防止这种事情发生,设置开机自启的脚本十分的重要,我们习惯性的做法就是编写一个重启脚本,然后在 /etc/rc.local 中去完成开机执行。例如下面这样:

$ cat /etc/rc.local
bash /root/script/restart.sh

这样的方法虽然可行,但并不优雅。今天我们就给大家介绍两种更好的实现方式:

2通过 Crontab 实现

Crontab 可以使用 @reboot 来执行主机启动之后的命令。首先在命令行输入:

$ crontab -e

然后添加以下内容:

@reboot /root/script/restart.sh

完成后,这个脚本就可以在重启的时候自动执行了。其它的一些进阶玩法:

  • 在启动完成后的指定时间内运行脚本
# 在启动 5 分钟后运行指定脚本
@reboot sleep 300 && /home/wwwjobs/clean-static-cache.sh

3通过 Systemd 实现

首先编写一个名为 restart 的 Systemd 服务:

$ vim /lib/systemd/system/restart.service

[Unit]
Description=restart
After=default.target

[Service]
ExecStart=/root/script/restart.sh

[Install]
WantedBy=default.target

然后启用这个 Systemd 服务:

$ systemctl daemon-reload
$ systemctl enable restart.service

标签:脚本,Systemd,重启,优雅,sh,Linux,开机,restart
From: https://www.cnblogs.com/Alwayslearn/p/16876583.html

相关文章

  • Linux修改成静态ip+虚拟机设置NAT
    一般改为静态ip都是想内网固定ip搭配虚拟机搭测试环境        打开虚拟机的这个路径,ifcf-enp2s0是自己的网卡名称vi/etc/sysconfig/network-scripts......
  • Linux配置环境变量
    Linux配置环境变量在配置Linux系统服务器的时候,我们常常需要设置系统环境变量,这篇文章就是总结几种常见的配置环境变量的方式。读取环境变量export命令读取当前系统......
  • Linux查看资源限制
    //显示所有资源限制ulimit-a real-timenon-blockingtime(microseconds,-R)unlimitedcorefilesize(blocks,-c)0datasegsize(......
  • Linux学习笔记(9)——学习Shell脚本
    学习shell脚本学习shell脚本一、什么是shell脚本1.1为什么要学习shell脚本1.2第一个脚本的编写与执行1.3建立shell脚本的良好编写习惯二、简单的shell脚本......
  • 皕杰报表的Linux部署
    对于一个新的linux系统,在上面部署皕杰报表需要下面的步骤: 1.首先得配置java环境变量,因为皕杰报表是纯java的,所以环境变量必不可少。2.然后把linux版的tomcat放到Linux系统......
  • 在PetaLinux工程中调试关键模块代码
    在PetaLinux工程中,与单板相关的UBoot、Linux等模块,经常需要编辑、调试。在旧版本中,可以为UBoot、Linux选择“ext-local-src”,指定UBoot、Linux的代码,从而使PetaLinux使......
  • 20201317-Linux-Thread 互斥测试
    #include<stdio.h>#include<stdlib.h>#include<pthread.h>//linux线程库#include<ctype.h>//测试和映射字符的库structarg_set{ char*fname; int......
  • Windows路径或者Linux路径映射成web路径进行访问代码
    packagecom.soft.mpms.zframe.config;importjava.io.File;importorg.springframework.context.annotation.Configuration;importorg.springframework.web.servlet.c......
  • ubuntu设置开机启动方法
    参考博客:https://blog.csdn.net/qq_32261101/article/details/123389338 linux服务管理有两种方式service和systemctl/lib/systemd/system/和/etc/systemd/system存......
  • How to Find Out What Linux Distribution You Are Using
    HowtoknownwhatLinuxDistributionIamusingnow.Allright,runthiscommandandyoucouldgetwhatyouneedinfromtheoutputresult19:12:17-androidyue~......