Skip to content

add-worker-cron

Schedule recurring tasks with Cloudflare Cron Triggers.

Overview

The add-worker-cron command creates scheduled jobs that run at specified intervals using Cloudflare's Cron Triggers, perfect for maintenance tasks, data synchronization, and automated workflows.

Usage

bash
/template add-worker-cron <job-name> <cron-expression> [options]

Parameters

  • <job-name> - Name of the cron job (e.g., cleanup, sync-data)
  • <cron-expression> - Cron schedule expression (e.g., "0 */6 * * *" for every 6 hours)

Options

  • --timeout - Maximum execution time in seconds (default: 30)
  • --retry - Enable automatic retries on failure
  • --alert - Send alerts on failure

Cron Expression Format

┌───────────── minute (0 - 59)
│ ┌───────────── hour (0 - 23)
│ │ ┌───────────── day of month (1 - 31)
│ │ │ ┌───────────── month (1 - 12)
│ │ │ │ ┌───────────── day of week (0 - 6)
│ │ │ │ │
* * * * *

Examples

Daily Cleanup at 2 AM

bash
/template add-worker-cron cleanup "0 2 * * *"

Hourly Data Sync

bash
/template add-worker-cron sync-data "0 * * * *" --retry

Weekly Report Generation

bash
/template add-worker-cron weekly-report "0 9 * * 1" --timeout 300

Every 15 Minutes Health Check

bash
/template add-worker-cron health-check "*/15 * * * *" --alert

What It Creates

Cron Configuration

  • Cron trigger in wrangler.toml
  • Handler function for the job
  • Error handling and logging
  • Optional retry logic

Generated Structure

src/
├── cron/
│   ├── [job-name]/
│   │   ├── handler.ts     # Cron job logic
│   │   ├── utils.ts       # Helper functions
│   │   └── types.ts       # Job-specific types
│   └── index.ts           # Cron exports

Example Cron Handler

typescript
// src/cron/cleanup/handler.ts
export async function handleCleanup(event: ScheduledEvent, env: Env) {
  console.log(`Cleanup job started at ${new Date(event.scheduledTime)}`);
  
  try {
    // Delete expired sessions
    const expired = await getExpiredSessions(env.DB);
    await deleteSessionBatch(env.DB, expired);
    
    // Clean up temporary files
    await cleanupTempFiles(env.R2_BUCKET);
    
    // Log success
    await env.ANALYTICS.track('cron_success', {
      job: 'cleanup',
      duration: Date.now() - event.scheduledTime,
    });
  } catch (error) {
    console.error('Cleanup job failed:', error);
    throw error; // Trigger retry if enabled
  }
}

Common Cron Patterns

Every X Minutes/Hours

bash
# Every 5 minutes
*/5 * * * *

# Every 2 hours
0 */2 * * *

# Every 30 minutes
*/30 * * * *

Daily Patterns

bash
# Every day at midnight
0 0 * * *

# Every day at 3:30 AM
30 3 * * *

# Twice daily (9 AM and 9 PM)
0 9,21 * * *

Weekly/Monthly

bash
# Every Monday at 9 AM
0 9 * * 1

# First day of month at midnight
0 0 1 * *

# Every Sunday at 2 AM
0 2 * * 0

Best Practices

  1. Idempotency: Jobs should be safe to run multiple times
  2. Timeouts: Set appropriate timeouts for long-running jobs
  3. Logging: Add comprehensive logging for debugging
  4. Monitoring: Track job success/failure metrics
  5. Error Handling: Implement proper error recovery

Common Use Cases

Database Maintenance

typescript
// Daily vacuum and analyze
export async function handleDbMaintenance(event: ScheduledEvent, env: Env) {
  await env.DB.exec('VACUUM');
  await env.DB.exec('ANALYZE');
}

Data Synchronization

typescript
// Sync with external API
export async function handleDataSync(event: ScheduledEvent, env: Env) {
  const lastSync = await env.KV.get('last_sync');
  const data = await fetchExternalData(lastSync);
  await syncToDatabase(env.DB, data);
  await env.KV.put('last_sync', new Date().toISOString());
}

Report Generation

typescript
// Generate and email weekly reports
export async function handleWeeklyReport(event: ScheduledEvent, env: Env) {
  const report = await generateReport(env.DB);
  await sendReportEmail(report);
  await storeReport(env.R2_BUCKET, report);
}

Monitoring and Alerts

Success/Failure Tracking

typescript
// Track job execution
await env.ANALYTICS.track('cron_execution', {
  job: jobName,
  status: 'success',
  duration: executionTime,
  timestamp: event.scheduledTime,
});

Alert Integration

bash
# Add alerting to any cron job
/template add-worker-cron critical-job "0 * * * *" --alert

Testing Cron Jobs

Local Testing

bash
# Manually trigger cron job
npm run cron:trigger cleanup

Test Handler

typescript
// test/cron/cleanup.test.ts
test('cleanup removes expired sessions', async () => {
  const event = createMockScheduledEvent();
  await handleCleanup(event, mockEnv);
  expect(await getSessionCount(mockEnv.DB)).toBe(0);
});

Performance Considerations

  • Cron jobs have 30-second CPU time limit
  • Use queues for long-running tasks
  • Batch operations for efficiency
  • Consider time zones for scheduling

Built with ❤️ for the AI Coding community, by Praney Behl