crontab配置
crontab命令
service crond start //启动服务
service crond stop //关闭服务
service crond restart //重启服务
定时任务设置:
#查看定时任务
crontab -l
#配置定时任务
crontab -e
#重启crontab 服务
service crond restart
#查看crontab 服务日志
tail -f /var/log/cron
配置定时任务 执行crontab -e
* * * * * /path/to/command
| | | | |
| | | | +---- 星期几(0-7)(0 或 7 表示星期天)
| | | +------ 月份(1-12)
| | +-------- 日期(1-31)
| +---------- 小时(0-23)
+------------ 分钟(0-59)
不同linux发行版本启动方式
linux发行版本没有service这个命令时:
/etc/init.d/cron stop
/etc/init.d/cron start
执行出现 /bin/systemctl 。。。。
可用以下命令操作
/bin/systemctl restart crond.service #启动服务
/bin/systemctl reload crond.service #重新载入配置
/bin/systemctl status crond.service #查看crontab服务状态
使用实例
实例1:每1分钟执行一次command
命令:
* * * * * command
实例2:每小时的第3和第15分钟执行
命令:
3,15 * * * * command
实例3:在上午8点到11点的第3和第15分钟执行
命令:
3,15 8-11 * * * command
实用操作
1、定时删除当前文件夹内上个月的文件
1,创建一个shell脚本
touch delete_file.sh
2,编写shell命令
脚本如下:
#!/bin/bash
# 获取当前日期和上个月的日期
last_month=$(date --date="last month" +"%Y-%m")
# 进入需要删除文件夹路径
cd /../../
# 使用 find 命令查找上个月的文件并删除
find . -type f -newermt "$last_month-01" ! -newermt "$(date +"%Y-%m-01")" -exec ls -l {} \;
find . -type f -newermt "$last_month-01" ! -newermt "$(date +"%Y-%m-01")" -exec rm -f {} \;
echo "已删除上个月的文件。"
3、执行crontab -e 添加定时任务
在尾行增加一行,${path}为脚本路径
3,15 * * * * sh /${path}/delete_file.sh
2、定时删除当前文件夹内上个月日期结尾的文件
1,创建一个shell脚本
touch delete_file.sh
2,编写shell命令
脚本如下:
#!/bin/bash
# 获取上个月的最后一天日期
last_month_date=$(date -d "$(date +%Y-%m-01) -1 month" +%Y-%m-%d)
cd /../../ # 需要删除文件夹路径
# 查找并删除文件名以上个月日期结尾的文件
find . -type f -name "*$last_month_date"
find . -type f -name "*$last_month_date" -exec rm {} \;
echo "已删除上个月的文件。"
3、执行crontab -e 添加定时任务
在尾行增加一行,${path}为脚本路径
3,15 * * * * sh /${path}/delete_file.sh
3、定时执行python脚本
1,创建一个shell脚本
touch run_main.sh
2,编写shell命令
脚本如下:
#!/bin/bash
# 检查结果文件是否存在
if [ -f "/opt/dtata/result.txt" ]; then
echo "/opt/dtata/result.txt exists. Exiting."
exit 0
fi
# 检查 model_main.py 是否正在运行
if pgrep -f "python.*model_main.py" > /dev/null; then
echo "model_main.py is already running."
exit 0
else
echo "model_main.py is not running. Starting the script..."
python model_main.py &
fi
echo "已执行"
3、执行crontab -e 添加定时任务
在尾行增加一行,${path}为脚本路径
3,15 * * * * sh /${path}/run_main.sh