1.延时任务
at now+1min //1分钟后执行
at 15:00 //15:00执行
touch /mnt/file{1..3} //设置任务
ctrl+d //
- at now+1min 字面意思等一分钟后再执行,其实为下一分钟的0秒执行;因为at命令是整分执行的
注:监控窗口中的时间为我截图时间,存在延迟;命令是按时执行的。
at -l //列出未执行的任务
at -c 3 //列出job号为3的任务的详细信息
at -r 3 //删除未执行且job号为3的任务
黑名单:
/etc/at.deny:默认存在,写入的用户将不能使用at命令
白名单:
/etc/at.allow:默认不存在,需要自己创建,用man 5 at.deny 查看得到的文件名,只有写入的用户才能使用at命令
注:root用户不受黑白名单限制;白名单和黑名单同时存在时,以白名单为准;如果创建白名单不写入任何用户,那么除root以外的所有用户将不能使用at命令,所以白名单慎用。
2.定时任务
systemctl status crond.server --开启才可执行定时任务
* * * * * //每分钟执行一次
*/2 * * * * //每两分钟执行一次
*/2 09,17 * * * //每天的9时(9:00--9:59)和17时(17:00--17:59),每两分钟执行一次
*/2 09-17 * * * //每天的9时到17时,每两分钟执行一次
*/2 09-17 1 * * //每月的1号9时到17时,每两分钟执行一次
*/2 09-17 1 3 * //每年3月1号的9时到17时,每两分钟执行一次
*/2 09-17 1 3 4 //每年3月的1号或3月的每周周四的9时到17时,每两分钟执行一次
crontab -e -u root //创建 -u root 指定用户为root用户
crontab -l -u root //列出,查看
crontab -r -u root //删除
(1)crontab -e -u root回车输入任务,wq退出保存,时间到了便会执行
/var/spool/cron/root //定时任务产生文件
查看此文件正是刚才创建任务的内容,删除此文件,定时任务将取消(2)黑白名单与at命令相同:/etc/cron.deny | /etc/cron.allow
以黑名单为例:lee
su - lee:不可用crontab -e
crontab -e -u lee:可以使用,他是以root身份指定lee用户执行crontab -e
(3)系统任务:cd /etc/cron.d
命令方式:
* * * * * root touch /mnt/file{1..9}
文件方式:
* * * * * root run-parts /westos
mkdir /westos
cd /westos
vim test.sh
#!/bin/bash
rm -fr /mnt/*
3.定时清理
- 有时我们需要清理系统中的缓存,但又不能清理正在使用的,便可使用定时清理功能
- windows中我们需要手动清理垃圾;而linux中存在定时清理,无需手动清理垃圾
- /usr/lib/tmpfiles.d:指定系统中临时文件的相关信息(目录,周期等等);然后再由定时任务定期执行清理命令,便可达到定期清理。
vim westos.conf
d /mnt/westos 777 root root 10s
//指定/mnt/westos/下的文件为临时文件,生命周期为10s
systemd-tmpfiles --create /usr/lib/tmpfiles.d/*
//此命令会创建刚才westos.conf中指定的/mnt/westos目录
systemd-tmpfiles --clean /usr/lib/tmpfiles.d/*
//清空/mnt/westos中的过期文件(超过周期的文件)
创建两个生命周期为10s 的文件,执行清理命令,由于file1已经超过10s,会被清理;file2没有超过10s,依然保留