高木のブログ

【Cloudflare Workers】Scheduled handler の開発方法

2023/09/02

Scheduled handler の開発方法のメモ

以下コマンドで Worker を作成する

$ wrangler generate sample-worker

いろいろ対話形式で質問に答えて、Worker の種類は Scheduled handler を選ぶ

サーバーを起動する

$ yarn wrangler dev --test-scheduled

リクエストする

$ curl "http://localhost:8787/__scheduled?cron=*+*+*+*+*"
Ran scheduled event

サーバーのログに Hello World! と出力される

Hello World!
[mf:inf] GET /__scheduled 200 OK (1ms)

これで開発に着手できる

補足

どうしてこの記事を書いたか

Worker を作成すると、以下のコードが生成される

src/index.ts
/**
 * Welcome to Cloudflare Workers! This is your first scheduled worker.
 *
 * - Run `wrangler dev --local` in your terminal to start a development server
 * - Run `curl "http://localhost:8787/cdn-cgi/mf/scheduled"` to trigger the scheduled event
 * - Go back to the console to see what your worker has logged
 * - Update the Cron trigger in wrangler.toml (see https://developers.cloudflare.com/workers/wrangler/configuration/#triggers)
 * - Run `wrangler deploy --name my-worker` to deploy your worker
 *
 * Learn more at https://developers.cloudflare.com/workers/runtime-apis/scheduled-event/
 */

export interface Env {
  // Example binding to KV. Learn more at https://developers.cloudflare.com/workers/runtime-apis/kv/
  // MY_KV_NAMESPACE: KVNamespace;
  //
  // Example binding to Durable Object. Learn more at https://developers.cloudflare.com/workers/runtime-apis/durable-objects/
  // MY_DURABLE_OBJECT: DurableObjectNamespace;
  //
  // Example binding to R2. Learn more at https://developers.cloudflare.com/workers/runtime-apis/r2/
  // MY_BUCKET: R2Bucket;
}

export default {
  async scheduled(
    controller: ScheduledController,
    env: Env,
    ctx: ExecutionContext
  ): Promise<void> {
    console.log(`Hello World!`);
  },
};

コメントに書いてあるやり方を実行してみると

$ wrangler dev --local
$ curl "http://localhost:8787/cdn-cgi/mf/scheduled"
{"name":"Error","message":"Handler does not export a fetch() function.","stack":"Error: Handler does not export a fetch() function.\n    at __facade_modules_fetch__ (index.js:106:11)\n    at __facade_invokeChain__ (index.js:39:10)\n    at Object.next (index.js:36:14)\n    at jsonError (index.js:66:32)\n    at __facade_invokeChain__ (index.js:39:10)\n    at __facade_invoke__ (index.js:42:10)\n    at Object.fetch (index.js:158:14)"}

コケた

ドキュメントを漁って、https://developers.cloudflare.com/workers/runtime-apis/scheduled-event/ にやり方が書いてあるのを見つけた


SNS でシェアする


ytkg

Written by ytkg, Twitter, GitHub