1.最初的方式
昨天配置一个定时任务,按照以往的经验(https://blog.csdn.net/JustDI0209/article/details/122946237),使用具有管理员权限的用户编辑定时任务:
sudo vim /etc/crontab
在文件的最后加入一行:
* * * * * useradmin /home/useradmin/test.sh
保存后退出,重启 crontab
sudo systemctl restart crond.service
test.sh:
#!/bin/bash
echo "test---" >> /home/useradmin/test.txt
补充命令:
sudo systemctl start crond.service //启动服务
sudo systemctl stop crond.service //关闭服务
sudo systemctl restart crond.service //重启服务
sudo systemctl reload crond.service //重新载入配置
sudo systemctl status crond.service //查看状态
crontab -u #设定某个用户的cron服务
crontab -l #显示crontab文件(显示已设置的定时任务)
crontab -e #编辑crontab文件(编辑定时任务)
crontab -r #删除crontab文件(删除定时任务)
crontab -i #删除crontab文件提醒用户(删除定时任务)
过了一会发现定时任务并没有执行,更离谱的是关闭此次 xshell 连接后,重新打开的 xshell 连接中 /etc/crontab 被清空了,恢复了最初的模样。
(图源网络,侵删)
看了一下版本:
cat /etc/redhat-release
是
CentOS Linux release 7.9.2009 (Core)
看来先前的方式是不行了。
2.使用 cron 文件
这种方式普通用户就可以。
创建 test.cron 文件,里面的内容如下:
* * * * * echo "test---" >> /home/XX/test.txt
保存退出。
然后执行:
crontab test.cron
过段时间后,查看 test.txt 文件,发现定时任务已经开始执行。
关闭 xshell 连接,重新开启一个,发现任务还在,并在执行。
3.使用 crontab -e 命令编辑
这种方式普通用户也可以。
先删除上次的定时任务,并重新创建个 test.txt ,然后创建个 testA.sh:
echo "test***" >> /home/appadmin/test.txt
然后执行:
crontab -e
写入:
* * * * * /home/appadmin/testA.sh
脚本要赋予执行权限:
chmod -R 777 testA.sh
然后查看效果
tail -f test.txt
发现定时任务开始执行。
然后关闭 xshell 连接,重新打开一个看看,定时任务依然在,并且在执行。
4.相关文件
#该文件中所列用户不允许使用crontab命令
/etc/cron.deny
# 该文件中所列用户允许使用crontab命令
/etc/cron.allow
#所有用户crontab文件存放的目录,以用户名命名
/var/spool/cron/
# crond日志文件
/var/log/cron