SCALE — Build Lab
開発パターン · CLOUDFLARE WORKER

Cron トリガーパターン

CATEGORY開発パターン TYPECloudflare Worker EFFORT60〜180分 DIFFICULTY
PRIMARY CODE
ts
// Cloudflare Workers - Cron Trigger
// wrangler.toml:
//   [triggers]
//   crons = ["0 9 * * *", "*/30 * * * *"]

interface Env {
  CACHE: KVNamespace;
  SLACK_TOKEN: string;
}

export default {
  async scheduled(event: ScheduledEvent, env: Env, ctx: ExecutionContext) {
    console.log('Cron triggered:', event.cron, new Date().toISOString());

    // 朝9時のみ
    if (event.cron === '0 9 * * *') {
      ctx.waitUntil(sendDailyReport(env));
    }
    // 30分おき
    if (event.cron === '*/30 * * * *') {
      ctx.waitUntil(refreshCache(env));
    }
  },
};

async function sendDailyReport(env: Env) {
  const data = await env.CACHE.get('today:metrics', 'json');
  // Slack 投稿等
}

async function refreshCache(env: Env) {
  const fresh = await fetch('https://api.example.com/data').then((r) => r.json());
  await env.CACHE.put('cache:data', JSON.stringify(fresh), { expirationTtl: 3600 });
}
前提条件
Tailwind CSS v4TypeScript 5
USE CASES
  • 日次レポート
  • 定期バックアップ

Cron トリガーパターン

:LiTarget: 用途

Cloudflare Workers の Cron Trigger で定期実行する標準パターン。

:LiSparkle: 特徴

  • cron式
  • KV更新
  • Slack通知連携

:LiCode: コード(コピペ用)

// Cloudflare Workers - Cron Trigger
// wrangler.toml:
//   [triggers]
//   crons = ["0 9 * * *", "*/30 * * * *"]

interface Env {
  CACHE: KVNamespace;
  SLACK_TOKEN: string;
}

export default {
  async scheduled(event: ScheduledEvent, env: Env, ctx: ExecutionContext) {
    console.log('Cron triggered:', event.cron, new Date().toISOString());

    // 朝9時のみ
    if (event.cron === '0 9 * * *') {
      ctx.waitUntil(sendDailyReport(env));
    }
    // 30分おき
    if (event.cron === '*/30 * * * *') {
      ctx.waitUntil(refreshCache(env));
    }
  },
};

async function sendDailyReport(env: Env) {
  const data = await env.CACHE.get('today:metrics', 'json');
  // Slack 投稿等
}

async function refreshCache(env: Env) {
  const fresh = await fetch('https://api.example.com/data').then((r) => r.json());
  await env.CACHE.put('cache:data', JSON.stringify(fresh), { expirationTtl: 3600 });
}

:LiHandPointer: 使い方

対象プロジェクトに該当ファイルをコピーして、props を流し込むだけ。

:LiAlertCircle: 注意事項

  • 依存パッケージを忘れず追加