3.0 KiB
Cron Setup (PM2 / self-hosted Linux)
Aplikasi punya beberapa endpoint cron yang harus di-trigger periodik dari luar. Karena deploy pakai PM2 di VPS Linux (bukan Vercel), trigger schedule pakai system crontab — zero dependency, OS-native.
Daftar cron job
| Endpoint | Schedule | Tujuan |
|---|---|---|
GET /api/cron/auto-complete-trips |
0 18 * * * (18:00 UTC = 01:00 WIB) |
Flip trip yang sudah lewat tanggal selesai dari OPEN/FULL ke COMPLETED. |
GET /api/cron/process-email-jobs |
*/5 * * * * (setiap 5 menit) |
Drain retry queue email — pick EmailJob status PENDING/FAILED (attempts<5), retry via Resend. |
Setup di server
1. Set CRON_SECRET di env production
Generate random secret 32 byte:
openssl rand -hex 32
Tambah ke file .env yang dibaca PM2 (atau yang pasti ter-load saat process boot):
CRON_SECRET="<hasil-openssl-tadi>"
Restart PM2 supaya proses re-load env:
pm2 restart setrip --update-env
2. Daftarkan crontab
Edit crontab user yang punya akses ke env (biasanya user yang menjalankan PM2):
crontab -e
Tambah baris (ganti https://your-domain.com dan <CRON_SECRET> sesuai env yang di-set di step 1):
# Setrip — auto-complete trips harian (jam 01:00 WIB)
0 18 * * * curl -fsS -H "Authorization: Bearer <CRON_SECRET>" https://your-domain.com/api/cron/auto-complete-trips >> /var/log/setrip-cron.log 2>&1
Verifikasi crontab tersimpan:
crontab -l
3. Siapkan file log
sudo touch /var/log/setrip-cron.log
sudo chown $(whoami) /var/log/setrip-cron.log
Test manual
Sebelum tunggu schedule, panggil endpoint langsung untuk verifikasi:
curl -fsS -H "Authorization: Bearer $CRON_SECRET" https://your-domain.com/api/cron/auto-complete-trips
Expected response:
- Belum ada trip yang lewat:
{"ok":true,"completed":0,"ids":[]} - Ada trip yang lewat:
{"ok":true,"completed":2,"ids":["clx...","cly..."]}
Kalau dapat 401: CRON_SECRET di env tidak match dengan header. Cek pm2 env <id>.
Kalau dapat 500: CRON_SECRET belum di-set di env.
Monitoring
Tail log cron:
tail -f /var/log/setrip-cron.log
Cek log app PM2 (untuk console.log dari endpoint):
pm2 logs setrip --lines 100 | grep cron
Troubleshooting
Cron jalan tapi tidak ada efek di DB:
- Cek
pm2 logs setripuntuk error. - Verifikasi waktu server:
date(output harus UTC kalau pakai schedule UTC).
Cron tidak jalan sama sekali:
- Cek service cron aktif:
systemctl status cron(Debian/Ubuntu) atausystemctl status crond(RHEL/CentOS). - Cek crontab terdaftar di user yang benar:
sudo crontab -u $(whoami) -l.
Secret bocor:
- Generate ulang
CRON_SECRET, update di.env+ crontab line, restart PM2.
Hari kalau pindah ke Vercel / PaaS lain
Tinggal hapus crontab line + bikin vercel.json (atau equivalent platform). Endpoint sudah platform-agnostic — proteksinya sama (header Authorization: Bearer <CRON_SECRET>).