# 🚀 Cron Job - Quick Start

## The Problem
Your cron job wasn't running because the script would exit immediately after setting up the schedules. There was no keep-alive mechanism to keep the process running.

## The Fix
✅ Added `setInterval()` to keep process alive  
✅ Added dev/prod mode detection  
✅ Dev mode: runs every 5/10 minutes for testing  
✅ Prod mode: runs at 1 AM / 2 AM daily  
✅ Added heartbeat logging every 30 minutes  

---

## Run It Now (Development)

```bash
# Terminal 1 - Your Next.js app
npm run dev

# Terminal 2 - Cron job
npm run cron
```

**What you'll see:**
```
============================================================
🚀 ZKTeco Cron Runner Started
============================================================
Environment: DEVELOPMENT
Current Time: 6/4/2026, 10:30:00 AM

Scheduled Jobs:
  🔧 DEV MODE: Every 5 minutes → employee sync
  🔧 DEV MODE: Every 10 minutes → attendance sync
============================================================

✓ Employee sync scheduled: */5 * * * *
✓ Attendance sync scheduled: */10 * * * *
```

---

## Development Schedules

| Job | Frequency | What it does |
|-----|-----------|--------------|
| Employee Sync | Every 5 minutes | Syncs employees from ZKTeco |
| Attendance Sync | Every 10 minutes | Syncs attendance + marks absents |
| Heartbeat | Every 30 minutes | Confirms process is alive |

---

## Test Immediately

Don't want to wait 5 minutes? Run manually:

```bash
# Run employee sync once
npm run sync-employees

# Run attendance sync once
npm run sync-attendance
```

Or edit `scripts/cron.ts` to run every minute:
```typescript
const employeeSchedule = "* * * * *"  // Every minute
const attendanceSchedule = "*/2 * * * *"  // Every 2 minutes
```

---

## Production Deployment

### Option 1: PM2 (Recommended)
```bash
npm install -g pm2
pm2 start npm --name "hrms-cron" -- run cron
pm2 save
pm2 startup
```

### Option 2: Docker
```bash
docker build -f Dockerfile.cron -t hrms-cron .
docker run -d --name hrms-cron --env-file .env hrms-cron
```

### Option 3: systemd
```bash
# Create /etc/systemd/system/hrms-cron.service
sudo systemctl enable hrms-cron
sudo systemctl start hrms-cron
```

See `docs/CRON_SETUP.md` for detailed instructions.

---

## Production Schedules

```bash
NODE_ENV=production npm run cron
```

| Job | Frequency | What it does |
|-----|-----------|--------------|
| Employee Sync | 1:00 AM daily | Syncs all employees from ZKTeco |
| Attendance Sync | 2:00 AM daily | Syncs previous day + marks absents |

---

## Logs

**Startup:**
```
🚀 ZKTeco Cron Runner Started
✓ Employee sync scheduled: */5 * * * *
✓ Attendance sync scheduled: */10 * * * *
```

**When running:**
```
[6/4/2026, 10:35:00 AM] 🔄 Employee sync started...
✅ Employee sync complete: created=5 updated=123 errors=0
```

**Heartbeat:**
```
💓 Heartbeat: 6/4/2026, 11:00:00 AM - Cron runner is alive
```

---

## Troubleshooting

### Not running?
```bash
# Check if process is running
ps aux | grep cron

# Check environment
echo $NODE_ENV
```

### Test connectivity
```bash
# Can you reach ZKTeco?
curl http://your-zkteco-host/iclock/api/transactions/
```

### Not triggering on schedule?
```bash
# Check current time
date

# Wait 5 minutes in dev mode for first employee sync
# Or run manually: npm run sync-employees
```

---

## What Was Changed

**File:** `scripts/cron.ts`

### Before ❌
```typescript
cron.schedule("0 1 * * *", async () => { ... })
cron.schedule("0 2 * * *", async () => { ... })
// Script exits immediately - schedules never run!
```

### After ✅
```typescript
const isDev = process.env.NODE_ENV !== "production"
const employeeSchedule = isDev ? "*/5 * * * *" : "0 1 * * *"
const attendanceSchedule = isDev ? "*/10 * * * *" : "0 2 * * *"

cron.schedule(employeeSchedule, async () => { ... })
cron.schedule(attendanceSchedule, async () => { ... })

// Keep process alive
setInterval(() => {}, 1000 * 60 * 60)
```

---

## Quick Reference

| Command | Purpose |
|---------|---------|
| `npm run cron` | Run cron job (dev mode) |
| `NODE_ENV=production npm run cron` | Run cron job (prod mode) |
| `npm run sync-employees` | Run employee sync once |
| `npm run sync-attendance` | Run attendance sync once |
| `pm2 logs hrms-cron` | View logs (PM2) |
| `pm2 restart hrms-cron` | Restart (PM2) |

---

## Next Steps

1. ✅ Run `npm run cron` in a separate terminal
2. ✅ Wait 5 minutes to see employee sync run
3. ✅ Check your database for synced records
4. ✅ See heartbeat every 30 minutes confirming it's alive
5. 🔜 Deploy to production with PM2

---

**For detailed documentation, see:** `docs/CRON_SETUP.md`
