4

linux利用cron定时服务来实现开机启动某些应用

 1 year ago
source link: https://blog.star7th.com/2023/02/2546.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

我会先介绍linux利用cron定时服务来实现开机启动的具体代码实现,然后再分析下这种开机启动方案的利弊。

代码语法例子

执行 crontab -e ,进入定时任务编辑模式。


# 假设我想开机执行的命令是 cd /var/www/node/ && npm run start 
# 意思是进入指定目录然后执行一个npm命令。 && 语法表示按顺序执行两个命令。
# 那么,如果要开机启动,我可以这么写cron 

@reboot cd /var/www/node/ && npm run start 

# @reboot  就是开机启动的意思。
# 如果要延迟启动,比如说延迟10秒,则可以这么写

@reboot sleep 10 &&  cd /var/www/node/ && npm run start

这种利用cron的启动方式非常方便,因为几乎所有linux发行版都自带cron服务,所以此方法使用范围很广。
在此方法之前,我一度利用 /etc/rc.local 文件来实现启动。但其实并不是最优秀选择。因为:

1,/etc/rc.local 文件 如果卡死可能导致系统无法启动
2,/etc/rc.local 文件启动的服务,其部分系统配置可能来不及生效。

对于上面的第2点,我详细解释下。比如说,我设置了linux的最大打开文件数,如果是用/etc/rc.local启动的,则可能我的应用还是会受到原始打开文件数设置的影响。

如果是我最上方说的cron方式启动,则是新的打开文件数配置。
这个经验,是我经过生产环境实践出来的。自此之后,我准备放弃/etc/rc.local的方式,统一都使用cron的方式来跑自脚本。
当然了,cron方式还是有它的弊端。相比Linux的systemctl服务,systemctl服务也能实现开机启动,同时还能停止服务,重启服务。这种方式确实更灵活一些。

但是systemctl是需要把脚本命令注册成服务的,这个就是另一个话题了。一般情况下,对于简单的执行脚本的场景,我还是推荐使用cron服务自启动。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK