Community코딩 & 개발github.com

waynesutton/convex-cron-jobs

백그라운드 작업을 위한 예약 함수 패턴: 간격 스케줄링, 크론 표현식, 작업 모니터링, 재시도 전략 및 장기 실행 작업 모범 사례

convex-cron-jobs란 무엇인가요?

이 스킬은 Convex에서 백그라운드 작업을 효율적으로 예약하고 실행하기 위한 패턴과 모범 사례를 제공합니다. 간격 스케줄링(Interval Scheduling)과 크론 표현식(Cron Expressions)을 모두 지원하여, 정기적인 데이터 정리, 이메일 발송, 상태 갱신 등 다양한 작업을 자동화할 수 있습니다. 또한 작업 모니터링, 재시도 전략, 그리고 장기 실행 작업을 안전하게 처리하는 방법을 포함하여, Convex 애플리케이션의 안정성을 높이는 데 중점을 둡니다. Convex의 `cronJobs` API를 기반으로 하며, 개발자는 복잡한 스케줄링 로직을 쉽게 구현하고 관리할 수 있습니다.

지원 대상~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은(는) 무엇을 하나요?

백그라운드 작업을 위한 예약 함수 패턴: 간격 스케줄링, 크론 표현식, 작업 모니터링, 재시도 전략 및 장기 실행 작업 모범 사례

소개

Convex는 cronJobs 모듈을 통해 예약 함수를 지원합니다. 이 스킬은 이 기능을 효과적으로 활용하기 위한 패턴과 모범 사례를 제공합니다.

주요 기능

  • 간격 스케줄링: 정해진 시간 간격으로 작업 실행
  • 크론 표현식: cron 패턴을 사용한 유연한 스케줄링
  • 작업 모니터링: 예약된 작업의 상태와 실행 이력 추적
  • 재시도 전략: 실패한 작업에 대한 자동 재시도 메커니즘
  • 장기 실행 작업: 오래 걸리는 작업을 조각내어 안전하게 처리

사용법

기본 예약 함수

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

const crons = cronJobs();

crons.interval("clear-uploaded-files", { hours: 4 }, internal.tasks.clearUploadedFiles);

export default crons;

크론 표현식 사용

crons.cron("weekly-report", "0 0 * * 0", internal.tasks.generateReport);

장기 실행 작업 패턴

작업이 Convex의 시간 제한을 초과할 수 있는 경우, 상태 기반 배치 처리 패턴을 사용하세요:

export const processBatch = internalMutation({
  handler: async (ctx) => {
    const batch = await ctx.db.query("items")
      .withIndex("status", (q) => q.eq("status", "pending"))
      .take(100);

    if (batch.length === 0) return; // 완료

    for (const item of batch) {
      await processItem(ctx, item);
      await ctx.db.patch(item._id, { status: "processed" });
    }

    await ctx.scheduler.runAfter(0, internal.tasks.processBatch);
  },
});

crons.interval("batch-process", { minutes: 1 }, internal.tasks.processBatch);

재시도 전략

export const sendEmail = internalMutation({
  handler: async (ctx, args) => {
    try {
      await emailService.send(args.to, args.content);
    } catch (error) {
      const retries = await ctx.db.query("retries")
        .withIndex("taskId", (q) => q.eq("taskId", args.taskId))
        .collect();
      
      if (retries.length < 3) {
        await ctx.db.insert("retries", {
          taskId: args.taskId,
          at: Date.now() + 60000 * Math.pow(2, retries.length), // 지수 백오프
        });
        await ctx.scheduler.runAfter(
          60000 * Math.pow(2, retries.length),
          internal.tasks.sendEmail,
          args
        );
      } else {
        console.error("이메일 전송 실패 (최대 재시도 초과)", args.taskId);
      }
    }
  },
});

모니터링

예약 함수의 상태를 모니터링하려면 Convex 대시보드의 cron jobs 섹션을 확인하세요. 각 작업의 마지막 실행 시간, 다음 실행 시간, 성공/실패 기록을 볼 수 있습니다.

모범 사례

  1. 작업을 멱등성(IDempotent)으로 설계: 동일한 작업이 여러 번 실행되어도 결과가 동일해야 합니다.
  2. 에러 처리: 모든 예약 함수에서 적절한 try-catch 블록을 사용하세요.
  3. 시간 초과 고려: 장기 실행 작업은 상태 기반 배치 패턴을 사용하세요.
  4. 스케줄링 겹침 방지: 이전 실행이 완료되기 전에 새 실행이 시작되지 않도록 해야 합니다.
  5. 환경별 구성: 개발, 스테이징, 프로덕션 환경에 따라 스케줄을 다르게 설정하세요.

참고 자료

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

관련 스킬