Linux下程序和脚本自动执行和启动方法汇总


本文的内容还没有实践过。

先记录一下机制。

Linux 发展到现在,自启动方式也出现了很多种机制。这也会让后来的人困惑。

为什么在网上找到的资料和我手里实际上看到的不一样。或者照着操作的没有起效。

rc.local

rc.local is being deprecated.

rc.local已经在越来越多的发行版中被废弃。

这也是很多人在/etc下到处找不到这个文件的原因。

甚至自己新建这个文件也没有用处。

因为Linux的初始进程已经基本上从 init变成了systemd

如果发行版已经将此机制废弃,网上有教程自己添加systemd的service来支持rc.local。

我觉得 还是别了吧。。。

如果他存在的话,会在所有启动程序机制的最后执行。

/etc/init.d 和 rcN.d

rcN.d是rc0.d~rc6.d 等一系列文件夹。数字序号表示对应的启动等级。

rc0: 停机(不能使用)
rc1: 单用户模式
rc2: 多用户模式,但是没有NFS
rc3: 完全多用户模式
rc4: 没有使用,系统预留
rc5: 图形界面模式
rc6: 重启模式(不能使用)

rcN.d中是一系列的软链接。链接到init.d中的启动脚本。

init.d中的脚本至少接受两种参数:

startstop

对应于rcN.d中的SK开头的文件名。如果是S 表示start这个脚本,传参start。如果是K开头,就会传stop来杀掉这个进程。

结合上面的运行模式。我发现在rc0 rc6下面全是K开头的文件。果然是 把线程都杀掉准备重启或关闭了。

另外值得一提的是,我们一般用桌面系统的话,是执行rc5中的脚本。

那嵌入式设备的话,可能是rc3

这几个目录不是先后顺序关系,就是不同模式的入口。

SK之后跟着一个数字,这个表示执行顺序。从小到大执行。

通过Systemd管理

现在是2022年6月。

目前比较推荐的用户定义自启动标准方式,应该是通过Systemd来管理。

下面引用:
How to write startup script for Systemd?

如果需要通过systemd运行自己的脚本:

你需要.service文件放在/etc/systemd/system之下:

For example:

the script: /usr/bin/vgaoff
the unit file: /etc/systemd/system/vgaoff.service

Now, edit the unit file. Its content depends on how your script works:

If vgaoff just powers off the gpu, e.g.:

exec blah-blah pwrOFF etc 

then the content of vgaoff.service should be:

[Unit]
Description=Power-off gpu

[Service]
Type=oneshot
ExecStart=/usr/bin/vgaoff  这个地方应该就是执行脚本

[Install]
WantedBy=multi-user.target

If vgaoff is used to power off the GPU and also to power it back on, e.g.:

这里表示可以对参数进行反应:

start() {
  exec blah-blah pwrOFF etc
}

stop() {
  exec blah-blah pwrON etc
}

case $1 in
  start|stop) "$1" ;;
esac

then the content of vgaoff.service should be:

[Unit]
Description=Power-off gpu

[Service]
Type=oneshot
ExecStart=/usr/bin/vgaoff start  你看 对脚本传参了
ExecStop=/usr/bin/vgaoff stop
RemainAfterExit=yes

[Install]
WantedBy=multi-user.target

如果没写脚本 就是单纯执行指令的情况如下

For the most trivial cases, you can do without the script and execute a certain command directly:

To power off:

[Unit]
Description=Power-off gpu

[Service]
Type=oneshot
ExecStart=/bin/sh -c "echo OFF > /whatever/vga_pwr_gadget/switch"

[Install]
WantedBy=multi-user.target

To power off and on:

[Unit]
Description=Power-off gpu

[Service]
Type=oneshot
ExecStart=/bin/sh -c "echo OFF > /whatever/vga_pwr_gadget/switch"
ExecStop=/bin/sh -c "echo ON > /whatever/vga_pwr_gadget/switch"
RemainAfterExit=yes

[Install]
WantedBy=multi-user.target

使能服务:
Enable the service
Once you’re done with the files, enable the service:

systemctl enable vgaoff.service

It will start automatically on next boot. You could even enable and start the service in one go with

systemctl enable --now vgaoff.service

as of systemd v.220 (on older setups you’ll have to start it manually).
For more details see systemd.service manual page.

和上一节比,systemd应该是更偏向用户那一侧,会在init.d的东西弄完之后执行。

crontab

crontab指令实际上是用来执行定时定期任务的。

颗粒度是分钟。

可以配置来在reboot的时候执行我们需要的指令。(这个测试的时候可以简单用用吧,不能当产品代码吧)。

与crond守护进程交互。

下面内容引用:
Crontab in Linux with 20 Useful Examples to Schedule Jobs
关于定时执行任务:Crontab的20个例子
在这里插入图片描述
从左到右依次为:
[分钟] [小时] [每月的某一天] [每年的某一月] [每周的某一天] [执行的命令]
注意:请留意每个选项的取值范围。

默认情况下,系统会编辑当前登录用户的crontab命令集合。

crontab -e

需要编辑其他用户的命令集合,需要使用到如下的命令:

crontab -u username -e

How to List Crontab
To view crontab entries of current users use the following command.

crontab -l

Use -u followed by the username to view crontab entries of the specified user.

crontab -u username -l

20 Useful Crontab Examples
Here is the list of examples for scheduling cron jobs in a Linux system using crontab.

  1. Schedule a cron to execute at 2am daily.
    This will be useful for scheduling database backup on a daily basis.
0 2 * * * /bin/sh backup.sh

Asterisk (*) is used for matching all the records.
2. Schedule a cron to execute twice a day.
Below example command will execute at 5 AM and 5 PM daily. You can specify multiple time stamps by comma-separated.

0 5,17 * * * /scripts/script.sh
  1. Schedule a cron to execute on every minutes.
    Generally, we don’t require any script to execute on every minute but in some cases, you may need to configure it.
* * * * *  /scripts/script.sh
  1. Schedule a cron to execute on every Sunday at 5 PM.
    This type of cron is useful for doing weekly tasks, like log rotation, etc.
0 17 * * sun  /scripts/script.sh
  1. Schedule a cron to execute on every 10 minutes.
    If you want to run your script on 10 minutes interval, you can configure like below. These types of crons are useful for monitoring.
*/10 * * * * /scripts/monitor.sh

*/10: means to run every 10 minutes. Same as if you want to execute on every 5 minutes use */5.

  1. Schedule a cron to execute on selected months.
    Sometimes we required scheduling a task to be executed for selected months only. Below example script will run in January, May and August months.
* * * jan,may,aug *  /script/script.sh
  1. Schedule a cron to execute on selected days.
    If you required scheduling a task to be executed for selected days only. The below example will run on each Sunday and Friday at 5 PM.
0 17 * * sun,fri  /script/script.sh
  1. Schedule a cron to execute on first sunday of every month.
    To schedule a script to execute a script on the first Sunday only is not possible by time parameter, But we can use the condition in command fields to do it.
0 2 * * sun  [ $(date +%d) -le 07 ] && /script/script.sh
  1. Schedule a cron to execute on every four hours.
    If you want to run a script on 4 hours interval. It can be configured like below.
0 */4 * * * /scripts/script.sh
  1. Schedule a cron to execute twice on every Sunday and Monday.
    To schedule a task to execute twice on Sunday and Monday only. Use the following settings to do it.
0 4,17 * * sun,mon /scripts/script.sh
  1. Schedule a cron to execute on every 30 Seconds.
    To schedule a task to execute every 30 seconds is not possible by time parameters, But it can be done by schedule same cron twice as below.
* * * * * /scripts/script.sh
* * * * *  sleep 30; /scripts/script.sh
  1. Schedule a multiple tasks in single cron.
    To configure multiple tasks with single cron, Can be done by separating tasks by the semicolon ( ; ).
* * * * * /scripts/script.sh; /scripts/scrit2.sh
  1. Schedule tasks to execute on yearly ( @yearly ).
    @yearly timestamp is similar to “0 0 1 1 *“.
    It will execute a task on the first minute of every year, It may useful to send new year greetings 🙂
@yearly /scripts/script.sh
  1. Schedule tasks to execute on monthly ( @monthly ).
    @monthly timestamp is similar to “0 0 1 * *“. It will execute a task in the first minute of the month. It may useful to do monthly tasks like paying the bills and invoicing to customers.
@monthly /scripts/script.sh
  1. Schedule tasks to execute on Weekly ( @weekly ).
    @weekly timestamp is similar to “0 0 * * mon“. It will execute a task in the first minute of the week. It may useful to do weekly tasks like the cleanup of the system etc.
@weekly /bin/script.sh
  1. Schedule tasks to execute on daily ( @daily ).
    @daily timestamp is similar to “0 0 * * *“. It will execute a task in the first minute of every day, It may useful to do daily tasks.
@daily /scripts/script.sh
  1. Schedule tasks to execute on hourly ( @hourly ).
    @hourly timestamp is similar to “0 * * * *“. It will execute a task in the first minute of every hour, It may useful to do hourly tasks.
@hourly /scripts/script.sh

18. Schedule tasks to execute on system reboot ( @reboot ).
@reboot is useful for those tasks which you want to run on your system startup. It will be the same as system startup scripts. It is useful for starting tasks in the background automatically.

@reboot /scripts/script.sh
  1. Redirect Cron Results to specified email account.
    By default, cron sends details to the current user where cron is scheduled. If you want to redirect it to your other account, can be done by setup MAIL variable like below
# crontab -l
MAIL=bob
0 2 * * * /script/backup.sh
  1. Taking backup of all crons to plain text file.
    I recommend keeping a backup of all jobs entry in a file. This will help you to recover crons in case of accidental deletion.

Check current scheduled cron:

# crontab -l
MAIL=rahul
0 2 * * * /script/backup.sh

Backup cron to text file:

# crontab -l > cron-backup.txt
# cat cron-backup.txt
MAIL=rahul
0 2 * * * /script/backup.sh

Removing current scheduled cron:

# crontab -r
# crontab -l
no crontab for root

Restore crons from text file:

# crontab cron-backup.txt
# crontab -l
MAIL=rahul
0 2 * * * /script/backup.sh
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小羊苏C

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值