Why Is My Cron Job Not Running? Step-by-Step Diagnosis
The most common failure with automated Cron tasks is that the script or command runs perfectly when you execute it manually in your terminal, but fails silently when invoked by the system daemon (cron). This occurs due to critical differences between your user session and the isolated environment of Cron.
Quick Diagnostics
systemctl enable --now cron (or crond)The most common failure with automated Cron tasks is that the script or command runs perfectly when you execute it manually in your terminal, but fails silently when invoked by the system daemon (cron). This occurs due to critical differences between your user session and the isolated environment of Cron.
Step-by-Step Solution
-
1
Step 1: Forzar el uso de rutas absolutas en comandos y scripts
Cron does not load the environment variables from your
.bashrcfile or inherit thePATHvariable from your interactive session. Therefore, it will not know where binaries likepython3,node, orgitare unless you use full paths:BASH# INCORRECTO: * * * * * python3 /home/usuario/script.py # CORRECTO (Usa "which python3" para verificar la ruta en tu sistema): * * * * * /usr/bin/python3 /home/usuario/script.py -
2
Step 2: Redirigir errores y logs de ejecución a un archivo físico
Since background tasks do not have a physical terminal to display error messages, you must force the system to write them to a log file in order to audit the exact reason for the failure:
BASH# Redirigir la salida estándar (1) y el canal de errores (2) a un log 0 5 * * * /usr/bin/bash /home/usuario/backup.sh >> /home/usuario/backup.log 2>&1 -
3
Step 3: Verificar que el demonio de Cron esté activo
Make sure that the service responsible for coordinating the scheduled task queue is running on your server:
BASHsudo systemctl status cron # En Debian/Ubuntu sudo systemctl status crond # En Arch/RHEL/CentOS
Prevention Advice
Recommended security practices:
- Always declare the
PATHvariable and the preferred shell explicitly at the top of your crontab configuration file (crontab -e) to ensure that execution does not rely on inherited external variables:PLAINTEXTSHELL=/bin/bash PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin