1.什么是定时任务
定点执行某个job
2.为什么用定时任务
电商秒杀(定点开启,定点关闭)、定时备份、定时清理、时间同步、定时执行(脚本)、定时爬虫、定时同步;
3.定时任务使用情况
- 系统使用:临时文件清理、系统信息采集、日志切割(系统日志、定时任务)
- 个人使用:定时备份、定时清理、时间同步
4.定时任务如何使用以及书写规范
* * * * * user-name command to be executed
[root@peachcat1 ~]# cat /etc/crontab
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
# For details see man 4 crontabs
# Example of job definition:
# .---------------- minute (0 - 59)分钟
# | .------------- hour (0 - 23)小时
# | | .---------- day of month (1 - 31)日
# | | | .------- month (1 - 12) OR 月jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat 周
# | | | | |
# * * * * * user-name command to be executed
*表示任意的时间都执行
-表示一个时间范围段
,表示分隔时段
/表示每隔n单位时间
5.使用crontab编写定时任务
参数 | 含义 |
---|---|
-e | 编辑定时任务 |
-l | 查看定时任务 |
-r | 删除定时任务 |
-u | 指定其他用户 |
6.crond注意事项
(1)给定时任务注释;
(2)将需要定期执行的任务写入shell脚本中,避免直接使用命令无法执行的情况;
(3)定时任务的结尾一定要有&>/dev/null或者将结果追加重定向>>/tmp/date.log文件;
(4)注意有些命令是无法执行的echo"123">>/tmp/test.log&>/dev/null;
(5)如果一定要使用命令,命令必须使用绝对路径;
7.crond如何备份
(1)通过查找/var/spool/cron中执行的记录,去推算任务执行的时间;
(2)定时备份/var/spool/cron/{username}
8.crond如何拒绝某个用户使用
(1)使用root将需要拒绝的用户加入/etc/cron.deny
(2)登录该普通用户,测试是否能编写定时任务