使用场景
linux 使用过程中有很多需要定期执行的任务,比如数据库备份,开机启动
一次和多次
在linux 中任务,有两种,一种是循环执行,执行多次的定时任务。一般使用crontab, 还有是只执行一次的定时任务,一般使用at.
Crontab
安全控制
crontab 是由cron(crond)这个系统服务来控制的。为了安全性,可以限制哪些账号可以使用crontab。
/etc/cron.allow: 将可以使用crontab的账号放入这个文件中
/etc/cron.deny: 将不能使用crontab的账号放入这个文件中
cron.allow 的优先级高于cron.deny.建议使用一个文件就好了,
[root@host etc]# ls -al | grep cron
-rw------- 1 root root 541 8月 9 2019 anacrontab
drwxr-xr-x. 2 root root 4096 2月 14 11:40 cron.d
drwxr-xr-x. 2 root root 4096 4月 29 2021 cron.daily
-rw------- 1 root root 0 8月 9 2019 cron.deny
drwxr-xr-x. 2 root root 4096 4月 29 2021 cron.hourly
drwxr-xr-x. 2 root root 4096 6月 10 2014 cron.monthly
-rw-r--r--. 1 root root 451 6月 10 2014 crontab
drwxr-xr-x. 2 root root 4096 6月 10 2014 cron.weekly
[root@host etc]#
一般服务器上默认会有一个cron.deny文件
crontab 语法介绍
[root@host etc]# crontab -h
crontab:无效选项 -- h
crontab: usage error: unrecognized option
Usage:
crontab [options] file
crontab [options]
crontab -n [hostname]
Options:
-u <user> define user
-e edit user's crontab
-l list user's crontab
-r delete user's crontab
-i prompt before deleting
-n <host> set host in cluster to run users' crontabs
-c get host in cluster to run users' crontabs
-s selinux context
-x <mask> enable debugging
crontab -e 会进入vi 的编辑画面,一行是一个任务。
每个任务有六个栏位
| 代表意义 | 分钟 | 小时 | 日期 | 月份 | 周 | 命令 |
|---|---|---|---|---|---|---|
| 数字范围 | 0-59 | 0-23 | 1-31 | 1-12 | 0-7 | XX命令 |
关于周中的0和7都代表周日
一些特殊字符
| 特殊字符 | 代表意义 |
|---|---|
| *(星号) | 代表任何时刻都接受的意思!举例来说,范例一内那个日、月、周都是 * , 就代表著『不论何月、何日的礼拜几的 12:00 都运行后续命令』的意思! |
| ,(逗号) | 代表一段时间范围内,举例来说, 8 点到 12 点之间的每小时的 20 分都进行一项工作: 0 3,6 * * * command 时间参数还是有五栏,不过第二栏是 3,6 ,代表 3 与 6 都适用! |
| -(减号) | 代表一段时间范围内,举例来说, 8 点到 12 点之间的每小时的 20 分都进行一项工作 20 8-12 * * * command 仔细看到第二栏变成 8-12 喔!代表 8,9,10,11,12 都适用的意思! |
| /n(斜线) | 那个 n 代表数字,亦即是『每隔 n 单位间隔』的意思,例如每五分钟进行一次,则: */5 * * * * command 很简单吧!用 * 与 /5 来搭配,也可以写成 0-59/5 ,相同意思!每五分钟执行一次 |
30 16 * * 5 mail friend@his.server.name < /home/dmtsai/friend.txt
#每周五16:30 给你的朋友发送一份邮件
开机执行脚本
@reboot sleep 300 && /home/start.sh
@reboot 表示重启开机的时候运行一次
string meaning
------ -----------
@reboot Run once, at startup.
@yearly Run once a year, "0 0 1 1 *".
@annually (same as @yearly)
@monthly Run once a month, "0 0 1 * *".
@weekly Run once a week, "0 0 * * 0".
@daily Run once a day, "0 0 * * *".
@midnight (same as @daily)
@hourly Run once an hour, "0 * * * *".