Tareas programadas
Las tareas programadas le permiten ejecutar automáticamente comandos o scripts en momentos específicos. Ubuntu 26.04 admite dos métodos: el cron tradicional y los temporizadores systemd más modernos.
Conceptos básicos de crontab
Administrar crontab
# Edit the current user's crontab
crontab -e
# View the current user's crontab
crontab -l
# Delete the current user's crontab
crontab -r
# Edit another user's crontab (requires root)
sudo crontab -u username -e
# View another user's crontab
sudo crontab -u username -lSintaxis de tiempo cron
Una expresión cron consta de 5 campos de tiempo:
┌──────── Minute (0-59)
│ ┌────── Hour (0-23)
│ │ ┌──── Day of month (1-31)
│ │ │ ┌── Month (1-12)
│ │ │ │ ┌ Day of week (0-7, both 0 and 7 mean Sunday)
│ │ │ │ │
* * * * * commandPersonajes especiales
| Personaje | Descripción | Ejemplo |
|---|---|---|
* | cualquier valor | * * * * * cada minuto |
, | Múltiples valores | 1,15,30 * * * * en los minutos 1, 15 y 30 |
- | Rango | 1-5 * * * * minutos 1 a 5 |
/ | paso | */10 * * * * cada 10 minutos |
Ejemplos comunes
# Run every minute
* * * * * /path/to/script.sh
# Run every hour (on the hour)
0 * * * * /path/to/script.sh
# Run daily at 3:00 AM
0 3 * * * /path/to/script.sh
# Run daily at 3:30 AM
30 3 * * * /path/to/script.sh
# Run every Monday at 2:00 AM
0 2 * * 1 /path/to/script.sh
# Run on the 1st of every month at midnight
0 0 1 * * /path/to/script.sh
# Run every 5 minutes
*/5 * * * * /path/to/script.sh
# Run at minutes 15 and 45 of every hour
15,45 * * * * /path/to/script.sh
# Run weekdays (Monday-Friday) at 9:00 AM
0 9 * * 1-5 /path/to/script.sh
# Run every hour from 8 AM to 6 PM daily
0 8-18 * * * /path/to/script.sh
# Run every 6 months (1st of January and July)
0 0 1 1,7 * /path/to/script.shPalabras clave especiales
# Equivalent shortcuts
@reboot # Run at system startup
@yearly # Run yearly = 0 0 1 1 *
@monthly # Run monthly = 0 0 1 * *
@weekly # Run weekly = 0 0 * * 0
@daily # Run daily = 0 0 * * *
@hourly # Run hourly = 0 * * * *
# Usage examples
@reboot /opt/myapp/start.sh
@daily /usr/local/bin/daily-backup.shConsejos prácticos para cron
Variables de entorno
El entorno de ejecución de cron difiere del entorno de shell del usuario: variables como PATH pueden estar incompletas:
# Set environment variables at the top of your crontab
SHELL=/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
MAILTO=admin@example.com
# Or use full paths in commands
0 3 * * * /usr/bin/rsync -av /source/ /backup/Registro
# Redirect output to a log file
0 3 * * * /path/to/script.sh >> /var/log/myscript.log 2>&1
# Discard all output
0 3 * * * /path/to/script.sh > /dev/null 2>&1
# Log only errors
0 3 * * * /path/to/script.sh > /dev/null 2>> /var/log/myscript-error.logNotificaciones por correo electrónico
# Set the email recipient in crontab
MAILTO=admin@example.com
# Disable email notifications
MAILTO=""Ver registros cron
# View via journalctl
journalctl -u cron.service
# Or check syslog
grep CRON /var/log/syslogDirectorios cron a nivel de sistema
Ubuntu proporciona varios directorios cron predefinidos:
# Place scripts in the appropriate directory for automatic execution
ls /etc/cron.hourly/ # Hourly
ls /etc/cron.daily/ # Daily
ls /etc/cron.weekly/ # Weekly
ls /etc/cron.monthly/ # Monthly# Add a script and ensure it has execute permission
sudo cp myscript.sh /etc/cron.daily/
sudo chmod +x /etc/cron.daily/myscript.shEl archivo de configuración cron a nivel de sistema /etc/crontab:
cat /etc/crontabSHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
# m h dom mon dow user command
17 * * * * root cd / && run-parts --report /etc/cron.hourly
25 6 * * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily )
47 6 * * 7 root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.weekly )
52 6 1 * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.monthly )Temporizadores systemd
Los temporizadores systemd son una alternativa moderna a cron, que ofrecen un control de tiempo más preciso y un mejor soporte de registro.
Ver temporizadores existentes
# List all active timers
systemctl list-timers --all
# Example output:
# NEXT LEFT LAST PASSED UNIT ACTIVATES
# Tue 2026-03-24 06:00:00 CST 2h left Mon 2026-03-23 06:00:00 CST 22h ago apt-daily.timer apt-daily.serviceCrear un temporizador personalizado
Para crear un temporizador se necesitan dos archivos: un archivo .service y un archivo .timer.
Paso 1: crear el archivo de servicio
sudo nano /etc/systemd/system/my-backup.service[Unit]
Description=Daily Backup Job
[Service]
Type=oneshot
ExecStart=/usr/local/bin/daily-backup.sh
User=root
StandardOutput=journal
StandardError=journalPaso 2: crear el archivo del temporizador
sudo nano /etc/systemd/system/my-backup.timer[Unit]
Description=Run Daily Backup at 3 AM
[Timer]
OnCalendar=*-*-* 03:00:00
Persistent=true
RandomizedDelaySec=300
[Install]
WantedBy=timers.targetPaso 3: activa el temporizador
sudo systemctl daemon-reload
sudo systemctl enable --now my-backup.timer
# Verify
systemctl list-timers | grep my-backup
# Manually trigger a test run
sudo systemctl start my-backup.service
# View execution logs
journalctl -u my-backup.serviceExpresiones de tiempo de OnCalendar
# Daily at 3 AM
OnCalendar=*-*-* 03:00:00
# Every Monday at 9 AM
OnCalendar=Mon *-*-* 09:00:00
# 1st of every month
OnCalendar=*-*-01 00:00:00
# Weekdays at 8 AM
OnCalendar=Mon..Fri *-*-* 08:00:00
# Every 15 minutes
OnCalendar=*:0/15
# Every hour
OnCalendar=hourly
# Every day
OnCalendar=daily
# Every week
OnCalendar=weeklyVerificar expresiones de tiempo:
# Test an expression and see upcoming trigger times
systemd-analyze calendar "Mon..Fri *-*-* 08:00:00"
systemd-analyze calendar "*:0/15"Temporizadores basados en eventos
Además de la programación basada en calendario, puede activar según eventos:
[Timer]
# Run 5 minutes after system boot
OnBootSec=5min
# Run 1 hour after the last execution completed
OnUnitActiveSec=1h
# Combined usage
OnBootSec=10min
OnUnitActiveSec=1hTemporizadores transitorios (ejecución retrasada única)
# Run a command after 30 minutes
systemd-run --on-active=30m /usr/local/bin/task.sh
# Run at a specific time
systemd-run --on-calendar="2026-03-25 10:00:00" /usr/local/bin/task.shComparación de temporizadores cron vs systemd
| Característica | cron | temporizadores del sistema |
|---|---|---|
| Complejidad de configuración | Sencillo, una línea | Requiere dos archivos |
| Registro | Se requiere configuración manual | Integrado con journalctl |
| Gestión de dependencia | No compatible | Admite dependencias de servicios |
| Precisión | La unidad mínima son minutos. | Preciso al segundo |
| Tareas perdidas | No ejecutado | Persistente = verdadero se pone al día |
| Control de recursos | No compatible | Admite límites de recursos de cgroup |
| Retraso aleatorio | No compatible | RandomizedDelaySec |
Mejores prácticas
- Utilice cron para tareas programadas simples, temporizadores systemd para tareas complejas.
- Registre siempre la salida para facilitar la resolución de problemas.
- Utilice rutas completas para evitar problemas con PATH.
- Evitar la superposición de tareas: las tareas de larga duración deben utilizar el bloqueo:
# Use flock to prevent task overlap
* * * * * /usr/bin/flock -n /tmp/myjob.lock /path/to/script.sh- Pruebe antes de implementar: primero ejecute los scripts manualmente para confirmar que funcionan correctamente.