Skip to Content
DocumentaçãoOperaçõesAdministração do SistemaTarefas agendadas

Tarefas agendadas

As tarefas agendadas permitem executar comandos ou scripts automaticamente em horários especificados. O Ubuntu 26.04 suporta dois métodos: o cron tradicional e os temporizadores systemd mais modernos.

Noções básicas do crontab

Gerenciando 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 -l

Sintaxe de tempo cron

Uma expressão cron consiste em 5 campos de tempo:

┌──────── 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) │ │ │ │ │ * * * * * command

Personagens Especiais

PersonagemDescriçãoExemplo
*Qualquer valor* * * * * a cada minuto
,Vários valores1,15,30 * * * * nos minutos 1, 15 e 30
-Alcance1-5 * * * * minutos 1 a 5
/Passo*/10 * * * * a cada 10 minutos

Exemplos comuns

# 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.sh

Palavras-chave especiais

# 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.sh

Dicas práticas do cron

Variáveis de ambiente

O ambiente de execução do cron difere do ambiente shell do usuário — variáveis como PATH podem 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.log

Notificações por e-mail

# Set the email recipient in crontab MAILTO=admin@example.com # Disable email notifications MAILTO=""

Visualizando registros do cron

# View via journalctl journalctl -u cron.service # Or check syslog grep CRON /var/log/syslog

Diretórios cron em nível de sistema

O Ubuntu fornece vários diretórios 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.sh

O arquivo de configuração cron em nível de sistema /etc/crontab:

cat /etc/crontab
SHELL=/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 do systemd

Os temporizadores do systemd são uma alternativa moderna ao cron, oferecendo controle de tempo mais preciso e melhor suporte de registro.

Visualizando 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.service

Criando um cronômetro personalizado

A criação de um cronômetro requer dois arquivos: um arquivo .service e um arquivo .timer.

Etapa 1: Crie o arquivo de serviço

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=journal

Etapa 2: Crie o arquivo do cronômetro

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.target

Etapa 3: Habilite o cronômetro

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.service

Expressões de tempo 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=weekly

Verifique as expressões de tempo:

# Test an expression and see upcoming trigger times systemd-analyze calendar "Mon..Fri *-*-* 08:00:00" systemd-analyze calendar "*:0/15"

Temporizadores baseados em eventos

Além do agendamento baseado em calendário, você pode acionar com base em 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=1h

Temporizadores transitórios (execução atrasada ú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.sh

Comparação de temporizadores cron e systemd

Recursocrontemporizadores do sistema
Complexidade de configuraçãoSimples, uma linhaRequer dois arquivos
RegistroConfiguração manual necessáriaIntegrado com jornalctl
Gerenciamento de dependênciasNão compatívelSuporta dependências de serviço
PrecisãoA unidade mínima é minutosPreciso ao segundo
Tarefas perdidasNão executadoPersistente=true alcança
Controle de recursosNão compatívelSuporta limites de recursos cgroup
Atraso aleatórioNão compatívelRandomizedDelaySec

Melhores práticas

  1. Use cron para tarefas agendadas simples, timers do systemd para tarefas complexas.
  2. Sempre registre a saída para facilitar a solução de problemas.
  3. Use caminhos completos para evitar problemas de PATH.
  4. Evite a sobreposição de tarefas — tarefas de longa duração devem usar bloqueio:
# Use flock to prevent task overlap * * * * * /usr/bin/flock -n /tmp/myjob.lock /path/to/script.sh
  1. Teste antes de implantar — execute os scripts manualmente primeiro para confirmar se funcionam corretamente.