liunx定时任务,centos定时任务
yum install cronie crontabs -y直接运行
crond -n 在前台运行
crond -i 守护进程在没有inotify支持的情况下运行systemctl service crond start # 启动服务
systemctl enable crond.service # 设置开机自启
sudo systemctl restart crond # 重启 cron 服务systemctl service crond.service # 检查服务是否正在运行crontab -l # 列出当前用户的定时任务(首次运行可能显示 "no crontab for root")
crontab -e # 编辑定时任务
crontab -r # 删除所有定时任务
* * * * * command_to_execute
五个星号分别代表:分钟(0-59)、小时(0-23)、日期(1-31)、月份(1-12)、星期(0-7,0 和 7 都代表周日)。每天凌晨 2 点执行 backup.sh 脚本:
0 2 * * * /path/to/backup.sh每小时的第 15 分钟执行 logrotate:
15 * * * * /usr/sbin/logrotate /etc/logrotate.conf10秒执行一次,如果不需要严格的 10 秒间隔,也可以通过错开多个 cron 任务实现近似效果:
* * * * * /path/to/your_command
* * * * * (sleep 10; /path/to/your_command)
* * * * * (sleep 20; /path/to/your_command)
* * * * * (sleep 30; /path/to/your_command)
* * * * * (sleep 40; /path/to/your_command)
* * * * * (sleep 50; /path/to/your_command)或者编写run_every_10s
#!/bin/bash
for i in {1..6}; do/path/to/your_command # 替换为你的实际命令sleep 10
done
添加可执行权限
chmod +x /usr/local/bin/run_every_10s.sh
编写定时任务
crontab -e
编写
* * * * * /usr/local/bin/run_every_10s.sh
写日记
# 每分钟向 /tmp/cron_test.txt 写入当前时间
* * * * * date >> /tmp/cron_test.txt 2>&1