简介: CSDN博客专家,专注Android/Linux系统,分享多mic语音方案、音视频、编解码等技术,与大家一起成长!
优质专栏:Audio工程师进阶系列【原创干货持续更新中……】🚀
优质专栏:多媒体系统工程师系列【原创干货持续更新中……】🚀
优质视频课程:AAOS车载系统+AOSP14系统攻城狮入门实战课【原创干货持续更新中……】🚀
人生格言: 人生从来没有捷径,只有行动才是治疗恐惧和懒惰的唯一良药.
🍉🍉🍉文章目录🍉🍉🍉
🌻1.前言
本篇目的:Ubuntu22.04之crontab创建定时任务
🌻2.crontab介绍
- Linux的
cron
是一个基于时间的任务调度程序,它可以用来安排那些需要周期性执行的任务。crontab
(cron table)是cron
服务的配置文件,它包含了定时任务的具体信息。 crontab
文件包含了六个字段,分别表示分钟、小时、日期、月份、星期几和要执行的命令。下面是一个简单的crontab
文件的例子:
# +---------------- minute (0 - 59)
# | +------------- hour (0 - 23)
# | | +---------- day of month (1 - 31)
# | | | +------- month (1 - 12)
# | | | | +---- day of week (0 - 6) (Sunday to Saturday)
# | | | | |
* * * * * 用户名 命令
在这个例子中,星号(*
)代表所有可能的值。这意味着,如果所有的字段都是星号,那么command to execute
将会每分钟执行一次。
crontab
还支持一些特殊字符,比如:
*
代表所有有效的值。,/
表示范围的值。比如1-5
代表1到5。?
表示不指定值。-
表示范围。L
表示月的最后一天。W
表示工作日(周一到周五)。
例如,如果你想每天早上8点执行某个命令,你可以这样设置:
0 8 * * * 用户名 命令
如果你想每个月的第一天早上8点执行某个命令,你可以这样设置:
0 8 1 * * 用户名 命令
crontab
还有一些特殊的用法,比如你可以使用@reboot
来设置系统重启时需要执行的任务。
要编辑crontab
文件,你可以使用crontab -e
命令。这将打开一个文本编辑器,你可以在这个编辑器里添加或修改定时任务。保存并退出编辑器后,cron
服务会自动加载新的crontab
文件。
要查看当前的crontab
文件,可以使用crontab -l
命令。
要删除当前的crontab
文件,可以使用crontab -r
命令,但是请谨慎使用,因为这会删除所有的定时任务。
总的来说,crontab
是Linux系统中一个非常有用的工具,可以帮助你自动化许多重复性的任务。
🌻3.解决方案
🐓3.1 创建定时任务
1.每天早上8点33分执行test.sh命令
# sudo sudo vim /etc/crontab
33 8 * * * root cd /home/shell && ./test.sh
- 33: 表示分钟
- 8:表示小时
- 8右一*:表示天(1-31天)
- 8右二*:表示月(1-12月)
- 8右三*:表示星期(星期一到星期日:1-7)
- root:表示用户名,这个必须有,否则语法报错。可以用自己的用户名,因为以上是root用户执行。
- cd /home/shell && ./test.sh:表示进入到指定目录,执行命令。
2.重启crontab服务
# service cron restart
3.查看crontab服务语法是否有问题
# service cron status
● cron.service - Regular background program processing daemon
Loaded: loaded (/lib/systemd/system/cron.service; enabled; vendor preset: enabled)
Active: active (running) since Tue 2024-06-18 20:51:24 CST; 9s ago
Docs: man:cron(8)
Main PID: 295505 (cron)
Tasks: 1 (limit: 76620)
Memory: 348.0K
CPU: 1ms
CGroup: /system.slice/cron.service
└─295505 /usr/sbin/cron -f -P
6月 18 20:51:24 localhost systemd[1]: Started Regular background program processing daemon.
6月 18 20:51:24 localhost cron[295505]: (CRON) INFO (pidfile fd = 3)
6月 18 20:51:24 localhost cron[295505]: (CRON) INFO (Skipping @reboot jobs -- not system startup)
- 以上说明服务正常启动,没有语法问题。
🐓3.2 每分钟执行一次
#每1分钟执行一次test02.sh
* * * * * root cd /home/shell && ./test02.sh
#每2分钟执行一次test02.sh
*/2 * * * * root cd /home/shell && ./test02.sh
#每3分钟执行一次test02.sh
*/3 * * * * root cd /home/shell && ./test02.sh
- root:表示root用户,可以换成自己的用户名。
🐓3.3 每小时执行一次
#每1小时执行一次test02.sh
* * * * * root cd /home/shell && ./test02.sh
#每2小时执行一次test02.sh
* */2 * * * root cd /home/shell && ./test02.sh
#每3小时执行一次test02.sh
* */3 * * * root cd /home/shell && ./test02.sh
- root:表示root用户,可以换成自己的用户名。
🐓3.4 每天执行一次
#每1天执行一次test02.sh
* * * * * root cd /home/shell && ./test02.sh
#每2天执行一次test02.sh
* * */2 * * root cd /home/shell && ./test02.sh
#每3天执行一次test02.sh
* * */3 * * root cd /home/shell && ./test02.sh