How to Schedule Cron Jobs on Cloudflare Workers

Modern Scheduled Task Architectures

In traditional server-centric environments, scheduling automated tasks requires configuring cron on dedicated Linux virtual machines or running continuous orchestrators like Kubernetes CronJobs. While functional, these configurations introduce infrastructure management overhead, single points of failure, and higher operating costs, especially for sparse or lightweight tasks. The transition to serverless architectures initially left scheduling in a gray area, often requiring developers to use external pinging services or cloud provider events to trigger tasks.

Cloudflare Workers Cron Triggers solve this challenge by allowing developers to schedule serverless functions directly on Cloudflare's global edge network. This setup guarantees execution without managing servers, provisioning virtual machines, or configuring complex cloud orchestrator pipelines.

The under-the-hood execution model of Cloudflare Workers Cron Triggers is fundamentally different from typical cron configurations. Instead of running on a single server in a specific data center, these tasks are triggered by a global scheduler that orchestrates execution across V8 isolates. When a scheduled trigger fires, Cloudflare spins up a V8 isolate in a nearby data center to execute the worker.

The runtime scheduler dynamically selects the execution node based on network traffic, system resources, and geographic location. Crucially, CPU resources are isolated, ensuring that cron jobs do not suffer from noisy neighbor issues or resource starvation.

Free tier workers are allocated up to 10ms of CPU time, while paid tier workers receive up to 50ms (or up to several minutes in CPU-bound billing profiles), providing sufficient compute to execute database cleanups, API synchronizations, or cache updates. Because these isolates execute in milliseconds, they represent a highly cost-efficient approach to recurring workloads.

Configuring Triggers in wrangler.toml

To schedule cron jobs, developers define the execution schedule within the "wrangler.toml" configuration file using standard crontab syntax. Cloudflare supports multiple triggers, allowing a single worker to execute on various schedules. Consider the following "wrangler.toml" snippet:

name = "edge-cron-worker"
main = "src/index.js"
compatibility_date = "2026-06-22"

[triggers]
crons = [
  "/15    *",  # Run every 15 minutes for system health checks
  "0 2   *",     # Run daily at 2:00 AM for database syncs
  "0 0   1"      # Run weekly on Monday at midnight for reporting
]

Once deployed using "wrangler deploy", the global scheduler registers these cron patterns and routes execution triggers to the worker at the designated intervals. The scheduler handles execution retries and monitors worker health automatically.

  • Crons array: Holds cron string expressions mapping trigger schedules.
  • Wrangler deploy: Syncs configuration parameters with the global control plane.
  • V8 Isolates: Launches scheduled function tasks within serverless sandbox zones.

Implementing the Scheduled Event Listener

In the worker codebase, scheduled executions are handled via the "scheduled" event listener in ES modules format. Unlike standard HTTP workers that receive an incoming request and return a response, scheduled workers receive a controller object containing details about the cron trigger, such as the timestamp and the specific cron expression that matched. To perform asynchronous operations without having the execution sandbox terminate prematurely, developers must use the "ctx.waitUntil()" method.

This method tells the V8 runtime to keep the isolate alive until the passed promise resolves, ensuring that background tasks complete successfully. Below is an example of an edge cron worker that executes a database cleanup task:

export default {
  async scheduled(event, env, ctx) {
    const cronExpression = event.cron;
    console.log(`Cron triggered at ${event.scheduledTime}: ${cronExpression}`);
    
    switch (cronExpression) {
      case "/15    *":
        ctx.waitUntil(performQuickHealthCheck(env));
        break;
      case "0 2   *":
        ctx.waitUntil(performDailyCleanup(env));
        break;
      case "0 0   1":
        ctx.waitUntil(generateWeeklyReport(env));
        break;
    }
  }
};

async function performQuickHealthCheck(env) {
  const res = await fetch("https://api.example.com/health");
  if (!res.ok) {
    await reportErrorToSlack("Health check failed", env);
  }
}

async function performDailyCleanup(env) {
  // Execute a D1 database delete statement for expired sessions
  const result = await env.DB.prepare(
    "DELETE FROM sessions WHERE expires_at < ?"
  ).bind(Date.now()).run();
  console.log(`Deleted ${result.meta.changes} expired sessions.`);
}

async function generateWeeklyReport(env) {
  // Aggregate data and email weekly summary
  const stats = await env.DB.prepare(
    "SELECT COUNT(*) as count FROM users WHERE created_at > ?"
  ).bind(Date.now() - 7  24  60  60  1000).first();
  await sendEmailReport(stats.count, env);
}

Error Mitigation and Queue Architectures

When writing scheduled workers, engineers must plan for error handling, retries, and rate limits. If a cron trigger fails because of an uncaught exception, the execution halts, and the scheduler reports the failure. Because there is no browser or API client to receive the error, you must integrate custom error logging using tools like Sentry or Logflare inside your catch blocks.

Furthermore, because scheduled tasks run on V8 isolates, they are subject to execution timeouts. If a task requires heavy processing, like processing thousands of image files, it should be broken down into smaller batches.

The scheduler can initiate the worker, which then publishes multiple tasks to a queue (like Cloudflare Queues), allowing concurrent consumer workers to process the queue items in parallel without hitting individual worker CPU limits. By decoupling ingestion and processing, you construct a highly scalable, rate-limited workflow at the edge.

Automated Edge Cron Orchestrations with Bramsley

Deploying cron jobs at the edge requires deep integration with overall system architecture and monitoring pipelines. At Bramsley, we build and deploy resilient background sync solutions using scheduled edge workers and Cloudflare Queues. At Bramsley Digital Studio, we design stateful processing systems that run on custom schedules, integrating edge databases like D1 and KV stores to manage batch data pipelines, clear stale caches, and synchronise inventory indexes globally with absolute reliability.

At Bramsley, our architectures eliminate single-point-of-failure servers while maintaining zero-maintenance overhead. Partner with us to implement highly scalable, edge-native scheduled automation that powers your enterprise applications.

Bramsley Digital Studio

Enterprise Digital Architecture

We engineer digital infrastructure that drives measurable B2B growth. Experts in Legacy System Migration and High-Performance Frontends.

Architecture Specs & Case Studies

Scale Your Operations

  • Legacy System Migration
  • Scalable Infrastructure
  • High-Performance Frontends
  • Global Edge Deployment