systemd & cron — Serviços e Agendamento
Criar um serviço systemd
Para rodar uma aplicação como serviço (inicia no boot, reinicia se cair):
# /etc/systemd/system/minhaapp.service
[Unit]
Description=Minha Aplicação
After=network.target
[Service]
Type=simple
User=deploy
WorkingDirectory=/opt/minhaapp
ExecStart=/usr/bin/python3 /opt/minhaapp/app.py
Restart=on-failure
RestartSec=5
Environment=ENV=production
[Install]
WantedBy=multi-user.target
Ativar e gerenciar:
sudo systemctl daemon-reload
sudo systemctl enable --now minhaapp
sudo systemctl status minhaapp
sudo systemctl restart minhaapp
sudo journalctl -u minhaapp -f # logs em tempo real
Túnel SSH reverso como serviço
Útil para acessar máquinas atrás de NAT/CGNAT.
# /etc/systemd/system/reverse-tunnel.service
[Unit]
Description=SSH Reverse Tunnel
After=network.target
[Service]
User=deploy
ExecStart=/usr/bin/ssh -NT -o ServerAliveInterval=60 -o ExitOnForwardFailure=yes \
-R 2222:localhost:22 usuario@servidor-publico.com
Restart=always
RestartSec=10
[Install]
WantedBy=multi-user.target
sudo systemctl enable --now reverse-tunnel
# Acesso: ssh -p 2222 deploy@servidor-publico.com
Timers do systemd (alternativa moderna ao cron)
# /etc/systemd/system/backup.service
[Service]
Type=oneshot
ExecStart=/opt/scripts/backup.sh
# /etc/systemd/system/backup.timer
[Timer]
OnCalendar=*-*-* 03:00:00 # todo dia às 3h
Persistent=true
[Install]
WantedBy=timers.target
sudo systemctl enable --now backup.timer
systemctl list-timers # ver próximos disparos
cron (clássico)
crontab -e # editar tarefas do usuário
crontab -l # listar
# ┌─ minuto (0-59)
# │ ┌─ hora (0-23)
# │ │ ┌─ dia do mês (1-31)
# │ │ │ ┌─ mês (1-12)
# │ │ │ │ ┌─ dia da semana (0-6, 0=domingo)
# * * * * * comando
0 3 * * * /opt/scripts/backup.sh # todo dia 3h
*/5 * * * * /opt/scripts/check.sh # a cada 5 min
0 8 * * 1 /opt/scripts/relatorio.sh # segundas 8h
0 0 1 * * /opt/scripts/mensal.sh # dia 1 de cada mês
Sempre use caminhos absolutos e redirecione a saída para log:
0 3 * * * /opt/scripts/backup.sh >> /var/log/backup.log 2>&1
systemd timer vs cron
| cron | systemd timer | |
|---|---|---|
| Logs | precisa redirecionar | integrado (journalctl) |
| Perdeu horário (máquina off) | não roda | Persistent=true recupera |
| Dependência de rede/serviço | não | sim (After=) |
Veja também: Linux · Bash & Scripts