0Pricing
Edge Computing with Cloudflare Workers & Deno · レッスン

Cron Triggersとスケジュール実行するWorkers

Cron TriggersでCloudflare Workersをスケジュール実行し、エッジで定期的なバックグラウンドタスクを自動化します。

「Cron Triggersとスケジュール実行するWorkers」はCoddyKit上の無料Edge Computing with Cloudflare Workers & Denoレッスンです。 これはレッスン4/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはEdge Computing with Cloudflare Workers & Deno学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 Edge Computing with Cloudflare Workers & Denoコースには全4レッスンが含まれています。

このレッスンの一部はまだ翻訳されておらず、英語で表示されています。

Why Scheduled Workers?

Beyond responding to HTTP requests, Workers can run on a schedule using Cron Triggers.

This is perfect for recurring jobs such as:

  • Cleaning up stale data in KV or D1
  • Sending daily report emails
  • Refreshing cached API responses
  • Aggregating analytics

No always-on server required, the Worker simply wakes up, runs, and goes back to sleep.

The scheduled() Handler

A scheduled Worker exports a scheduled() handler instead of (or alongside) fetch().

Cloudflare invokes it automatically at the times you define in cron expressions.

export default {
  async scheduled(event, env, ctx) {
    console.log('Triggered at: ' + event.scheduledTime);
  }
};

Configuring Cron in wrangler.toml

Cron schedules live in your wrangler.toml under the [triggers] section.

You can declare multiple cron expressions, each one fires the same scheduled() handler.

[triggers]
crons = ["0 * * * *", "*/15 * * * *"]

Cron Expression Syntax

Cloudflare cron expressions have five fields: minute, hour, day-of-month, month, day-of-week.

  • 0 0 * * * means midnight UTC every day
  • */5 * * * * means every 5 minutes
  • 0 9 * * 1 means 09:00 UTC every Monday

All times are in UTC.

Distinguishing Multiple Crons

When you register several cron schedules, use event.cron to tell which one fired.

This lets one Worker handle many jobs.

export default {
  async scheduled(event, env, ctx) {
    if (event.cron === '0 0 * * *') {
      await runDailyCleanup(env);
    } else if (event.cron === '*/15 * * * *') {
      await refreshCache(env);
    }
  }
};

Using waitUntil for Long Tasks

Just like in fetch(), the ctx.waitUntil() method keeps the Worker alive until a promise resolves.

Use it to ensure background async work completes before the invocation ends.

async scheduled(event, env, ctx) {
  ctx.waitUntil(syncRemoteData(env));
}

Accessing Bindings in scheduled()

The env argument exposes all your bindings: KV, D1, R2, Queues, secrets.

A scheduled cleanup might delete expired KV keys.

async scheduled(event, env, ctx) {
  const list = await env.MY_KV.list({ prefix: 'session:' });
  for (const key of list.keys) {
    await env.MY_KV.delete(key.name);
  }
}

Testing Crons Locally

Wrangler lets you test scheduled handlers without waiting for the real schedule.

Run wrangler dev and trigger via the test endpoint, or use the CLI flag.

wrangler dev --test-scheduled
# then visit:
# http://localhost:8787/__scheduled?cron=0+*+*+*+*

Combining fetch() and scheduled()

A single Worker can export both handlers.

This is handy when the same logic serves HTTP requests and runs on a timer.

export default {
  async fetch(request, env) {
    return new Response('Hello from fetch');
  },
  async scheduled(event, env, ctx) {
    console.log('Hello from cron');
  }
};

Monitoring Scheduled Runs

Cron invocations appear in the Cloudflare dashboard and in wrangler tail logs.

Watch for failures, a thrown error means the job did not complete, and there is no automatic retry for cron triggers.

wrangler tail --format pretty

Limits & Best Practices

Keep scheduled jobs efficient:

  • Stay within CPU time limits, offload heavy work to Queues
  • Make jobs idempotent so reruns are safe
  • Avoid sub-minute schedules unless necessary
  • Log results for observability

Quick Check

Which property tells you which cron schedule triggered the handler?

Recap

You learned how to run Workers on a schedule:

  • Export a scheduled() handler
  • Define schedules in [triggers] crons
  • Use five-field UTC cron expressions
  • Route with event.cron and keep work alive with ctx.waitUntil()
  • Test with --test-scheduled and monitor with wrangler tail

Cron Triggers turn Workers into reliable edge-native background job runners.

よくある質問

「Cron Triggersとスケジュール実行するWorkers」レッスンは無料ですか?

はい。「Cron Triggersとスケジュール実行するWorkers」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Edge Computing with Cloudflare Workers & Denoコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Edge Computing with Cloudflare Workers & Denoコースには全4レッスンが含まれています。

「Cron Triggersとスケジュール実行するWorkers」で何を学びますか?

Cron TriggersでCloudflare Workersをスケジュール実行し、エッジで定期的なバックグラウンドタスクを自動化します。 ブラウザで直接実行するハンズオンコードでEdge Computing with Cloudflare Workers & Denoを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

Edge Computing with Cloudflare Workers & Denoを始めるのに経験は必要ですか?

事前経験は必要ありません。CoddyKitのEdge Computing with Cloudflare Workers & Denoは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン4/4です。

「Cron Triggersとスケジュール実行するWorkers」レッスンにはどのくらい時間がかかりますか?

ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。

このEdge Computing with Cloudflare Workers & Denoレッスンでコードを書いて実行できますか?

はい。すべてのEdge Computing with Cloudflare Workers & Denoレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。

このコースのすべてのレッスン

  1. WebSocketsとリアルタイム通信
  2. Queuesと非同期タスク
  3. Service Bindingsと連携
  4. Cron Triggersとスケジュール実行するWorkers
← Edge Computing with Cloudflare Workers & Denoに戻る