Docs Examples Cron → Function → KV
Cron

Cron → Function → KV

Run nightly jobs and persist state between runs.

The Pattern

Cron Function KV

Why this pattern?

  • No servers: No cron daemon to maintain or monitor
  • Timezone support: Schedule in any timezone
  • State persistence: KV stores sync cursors, counters, and metadata
  • Automatic invocation: We call your function on schedule
Example implementation
// 1. Create a cron job that triggers your function nightly
await fetch('https://api.rocketstack.dev/cron', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer YOUR_API_KEY',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    name: 'nightly-sync',
    schedule: { expression: '0 2 * * *' },  // Every day at 2 AM UTC
    deliveryTarget: {
      type: 'function',
      functionId: 'fn_nightly_sync'
    }
  })
});

// 2. Your Function runs the sync and stores state in KV
// fn_nightly_sync
export default async function handler(event) {
  // Get last sync timestamp from KV (key in path)
  const lastSyncRes = await fetch('https://api.rocketstack.dev/kv/items/sync-last', {
    headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
  });
  const lastSync = lastSyncRes.ok ? await lastSyncRes.json() : { data: {} };

  // Fetch new data since last sync
  const newData = await fetchDataSince(lastSync.data?.value?.timestamp);

  // Process the data
  await processRecords(newData);

  // Update last sync timestamp in KV
  await fetch('https://api.rocketstack.dev/kv/items/sync-last', {
    method: 'PUT',
    headers: {
      'Authorization': 'Bearer YOUR_API_KEY',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      value: { timestamp: Date.now(), records: newData.length }
    })
  });

  return { synced: newData.length };
}
Free tier available

Ready to start building?

Create your free account and integrate infrastructure primitives in minutes.