Communityコーディング&開発github.com

waynesutton/convex-cron-jobs

Convexにおけるバックグラウンドタスクのためのスケジュール関数パターン:インターバルスケジューリング、cron式、ジョブ監視、リトライ戦略、長時間実行タスクのベストプラクティスを提供します。

convex-cron-jobs とは?

このスキルは、Convexプラットフォーム上でバックグラウンドタスクをスケジュール実行するための包括的なパターンとベストプラクティスを提供します。主な機能として、インターバルスケジューリング、cron式による柔軟なスケジューリング、ジョブの監視、リトライ戦略、そして長時間実行タスクの効率的な処理方法をカバーしています。Convexの`crons.ts`ファイルと`convex/schema.ts`を活用し、`cronJobs` APIを使用して定義済みのスケジュールを設定します。開発者はこのスキルを使用することで、信頼性の高いバックグラウンド処理を実装し、ジョブの状態管理やエラーハンドリングを簡素化できます。また、ジョブの進行状況を追跡するためのデータベーステーブルや、失敗したジョブのリトライメカニズムも含まれており、本番環境での堅牢な運用を支援します。このスキルはClaude CodeやClineなどのAIエージェントと互換性があり、Convexプロジェクトへの統合が容易です。

対応~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/waynesutton/convexskills/tree/main/skills/convex-cron-jobs

Installed? Explore more コーディング&開発 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

お気に入りのAIに質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

convex-cron-jobs は何をしますか?

バックグラウンドタスクのためのスケジュール関数パターン:インターバルスケジューリング、cron式、ジョブ監視、リトライ戦略、長時間実行タスクのベストプラクティスを提供します。

概要

Convexは、crons.ts ファイルを使用してバックグラウンドタスクをスケジュールするための cronJobs API を提供します。このスキルでは、これらのジョブを効果的に管理するためのパターンについて説明します。

主要な概念

1. インターバルスケジューリング

一定の間隔でジョブを実行します。

// convex/crons.ts
import { cronJobs } from "convex/server";
import { internal } from "./_generated/api";

const crons = cronJobs();

crons.interval("cleanup old data", { hours: 1 }, internal.tasks.cleanup);

export default crons;

2. cron式

特定の時間や日時にジョブを実行します。

crons.cron("daily report", "0 9 * * 1-5", internal.tasks.generateReport);

3. ジョブ監視

convex/schema.ts にジョブの状態を追跡するためのテーブルを定義します。

// convex/schema.ts
import { defineSchema, defineTable } from "convex/server";
import { v } from "convex/values";

export default defineSchema({
  jobStatus: defineTable({
    jobName: v.string(),
    status: v.union(v.literal("running"), v.literal("completed"), v.literal("failed")),
    startedAt: v.number(),
    completedAt: v.optional(v.number()),
    error: v.optional(v.string()),
    metadata: v.optional(v.any()),
  }).index("by_jobName", ["jobName"]),
});

4. リトライ戦略

ジョブが失敗した場合のリトライメカニズムを実装します。

// convex/tasks.ts
import { mutation } from "./_generated/server";
import { v } from "convex/values";

export const processWithRetry = mutation({
  args: { jobName: v.string(), maxRetries: v.optional(v.number()) },
  handler: async (ctx, args) => {
    const maxRetries = args.maxRetries ?? 3;
    let retries = 0;

    while (retries < maxRetries) {
      try {
        // 実際のジョブ処理
        await performJob(ctx);
        break; // 成功したらループを抜ける
      } catch (error) {
        retries++;
        if (retries >= maxRetries) {
          throw new Error(`ジョブ ${args.jobName} は最大リトライ回数 ${maxRetries} 回を超えました`);
        }
        // 指数バックオフ
        await ctx.scheduler.runAfter(1000 * Math.pow(2, retries), internal.tasks.retry, {
          jobName: args.jobName,
          attempt: retries,
        });
      }
    }
  },
});

5. 長時間実行タスクのベストプラクティス

  • タスクを小さなステップに分割する
  • 進捗状況をデータベースに保存する
  • ctx.scheduler.runAfter を使用してタスクをチェーンする
  • メモリ制限に注意する

使用例

以下は、1時間ごとに実行される監視ジョブの完全な例です。

// convex/crons.ts
import { cronJobs } from "convex/server";
import { internal } from "./_generated/api";

const crons = cronJobs();

crons.interval("monitor system health", { hours: 1 }, internal.monitoring.checkHealth);

export default crons;
// convex/monitoring.ts
import { mutation } from "./_generated/server";

export const checkHealth = mutation({
  handler: async (ctx) => {
    const healthStatus = await performHealthCheck();
    await ctx.db.insert("jobStatus", {
      jobName: "monitor system health",
      status: "completed",
      startedAt: Date.now(),
      completedAt: Date.now(),
      metadata: { status: healthStatus },
    });
  },
});

参考リンク

Individual skills in this repo

This repo contains 13 individual skills — each has its own dedicated page.

waynesutton/avoid-feature-creep

Prevent feature creep when building software, apps, and AI-powered products. Use this skill when planning features, reviewing scope, building MVPs, managing backlogs, or when a user says "just one more feature." Helps developers and AI agents stay focused, ship faster, and avoid bloated products.

waynesutton/convex

Umbrella skill for all Convex development patterns. Routes to specific skills like convex-functions, convex-realtime, convex-agents, etc.

waynesutton/convex-agents

Building AI agents with the Convex Agent component including thread management, tool integration, streaming responses, RAG patterns, and workflow orchestration

waynesutton/convex-best-practices

Guidelines for building production-ready Convex apps covering function organization, query patterns, validation, TypeScript usage, error handling, and the Zen of Convex design philosophy

waynesutton/convex-component-authoring

How to create, structure, and publish self-contained Convex components with proper isolation, exports, and dependency management

waynesutton/convex-file-storage

Complete file handling including upload flows, serving files via URL, storing generated files from actions, deletion, and accessing file metadata from system tables

waynesutton/convex-functions

Writing queries, mutations, actions, and HTTP actions with proper argument validation, error handling, internal functions, and runtime considerations

waynesutton/convex-http-actions

External API integration and webhook handling including HTTP endpoint routing, request/response handling, authentication, CORS configuration, and webhook signature validation

waynesutton/convex-migrations

Schema migration strategies for evolving applications including adding new fields, backfilling data, removing deprecated fields, index migrations, and zero-downtime migration patterns

waynesutton/convex-realtime

Patterns for building reactive apps including subscription management, optimistic updates, cache behavior, and paginated queries with cursor-based loading

waynesutton/convex-schema-validator

Defining and validating database schemas with proper typing, index configuration, optional fields, unions, and migration strategies for schema changes

waynesutton/convex-security-audit

Deep security review patterns for authorization logic, data access boundaries, action isolation, rate limiting, and protecting sensitive operations

waynesutton/convex-security-check

Quick security audit checklist covering authentication, function exposure, argument validation, row-level access control, and environment variable handling

関連スキル