Edge Computing with Cloudflare Workers & Deno · Lekcja

Wyzwalacze Cron i zaplanowane Workers

Uruchamiaj Cloudflare Workers według harmonogramu za pomocą Cron Triggers, automatyzując cykliczne zadania w tle na edge.

Lekcja 4 z 413 kroki

Wyzwalacze Cron i zaplanowane Workers to bezpłatna lekcja Edge Computing with Cloudflare Workers & Deno na CoddyKit. To lekcja 4 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej Edge Computing with Cloudflare Workers & Deno, a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs Edge Computing with Cloudflare Workers & Deno zawiera 4 lekcji w sumie.

Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.

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.

Bezpłatny start

Ucz się Edge Computing with Cloudflare Workers & Deno dzięki korepetycjom AI — za darmo

Pisz i uruchamiaj kod w przeglądarce, otrzymuj natychmiastową pomoc od korepetytora AI dostępnego 24/7 i kontynuuj naukę w sieci lub w aplikacji.

Kursy
12
Lekcje
47

Często zadawane pytania

Czy lekcja „Wyzwalacze Cron i zaplanowane Workers” jest bezpłatna?

Tak — pełny tekst „Wyzwalacze Cron i zaplanowane Workers” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu Edge Computing with Cloudflare Workers & Deno, przejdź na CoddyKit PRO. Kurs Edge Computing with Cloudflare Workers & Deno zawiera 4 lekcji w sumie.

Co nauczysz się w „Wyzwalacze Cron i zaplanowane Workers”?

Uruchamiaj Cloudflare Workers według harmonogramu za pomocą Cron Triggers, automatyzując cykliczne zadania w tle na edge. Ćwiczysz Edge Computing with Cloudflare Workers & Deno z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.

Czy potrzebuję doświadczenia, aby zacząć Edge Computing with Cloudflare Workers & Deno?

Nie wymagamy żadnego doświadczenia. Edge Computing with Cloudflare Workers & Deno w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 4 z 4.

Ile czasu zajmuje lekcja „Wyzwalacze Cron i zaplanowane Workers”?

Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.

Czy mogę pisać i uruchamiać kod w tej lekcji Edge Computing with Cloudflare Workers & Deno?

Tak. Każda lekcja Edge Computing with Cloudflare Workers & Deno zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.

Wszystkie lekcje w tym kursie

  1. WebSockets i komunikacja w czasie rzeczywistym
  2. Kolejki i zadania asynchroniczne
  3. Wiązania usług i integracje
  4. Wyzwalacze Cron i zaplanowane Workers
← Powrót do Edge Computing with Cloudflare Workers & Deno