linux crontab任务不执行踩坑指南

781 阅读1分钟

踩坑场景

crontab 设置了定时任务,虽然时间到了,任务却没有执行 在这里插入图片描述

避坑指南

一、查看crontab任务是否执行

首先要确认任务执行了,需要查看crontab的执行日志 crontab日志目录:/var/log/cron 在这里插入图片描述 确认任务执行了就可以断定任务是执行过程失败了

二、任务执行过程失败的常见原因

1. 执行文件无执行权限

00 10 * * 6 /mnt/root/test.sh

需要为执行文件添加执行权限 chmod 777 /mnt/root/test.sh

2. 执行文件内部命令没有指定绝对路径

eg

#!/bin/bash
cd /mnt/root
python3 test.py

此脚本的python3需要改为绝对路径,见下文

#!/bin/bash
cd /mnt/root
/mnt/anaconda3/envs/py36/bin/python3 test.py

3. 打印内容有中文,控制台不支持显示中文,需在执行前引入对应环境变量,指定为utf-8格式

#!/bin/bash
export LANG=“en_US.UTF-8” >> ~/.bash_profile
source ~/.bash_profile
cd /mnt/root
/mnt/anaconda3/envs/py36/bin/python3 test.py

4.更多执行错误可直接将执行日志指定目录文件输出,查看原因

47 13 * * * /mnt/root/test.sh > /mnt/root/output.log 2>&1