# @convex-dev/crons 中文文档

规范地址：https://npmcn.com/package/%40convex-dev/crons/

版本：0\.2\.3
npm 元数据更新时间：2026-10-10T00:55:58.185Z
中文译文更新时间：2026-11-10T17:46:25.308Z
软件包许可：Apache-2\.0

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40convex-dev/crons
原文对照：https://npmcn.com/package/%40convex-dev/crons/?lang=original
项目主页：https://github.com/get-convex/crons#readme
源码仓库：https://github.com/get-convex/crons

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：107 kB，49 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- 运行依赖：1 个
- peer 依赖：convex ^1\.24\.8
- 首次发布：2024-09-20T02:00:55.202Z
- 最新版本发布：2026-10-10T00:55:57.995Z
- 近 30 天下载量：357125（2026-10-11 至 2026-11-09，npm 官方下载统计）
- 已发布版本数：18（近 12 个月 4 个）

## 中文简介

用于定期工作调度的对流组件 .

## 安装

```sh
npm install @convex-dev/crons
```

也可以使用：`pnpm add @convex-dev/crons`、`yarn add @convex-dev/crons`、`bun add @convex-dev/crons`

## README

# Crons Convex 组件

[![npm version](https://badge.fury.io/js/@convex-dev%2Fcrons.svg)](https://badge.fury.io/js/@convex-dev%2Fcrons)

Convex 组件提供了注册和管理克龙的功能 运行时的工作。 Convex有内在的支持,但必须 部署时采用静态定义。 此库允许动态 在运行时登记工作.

```ts
// Register a cron to run once per day.
const daily = await crons.register(
  ctx,
  { kind: "cron", cronspec: "0 0 * * *" },
  internal.example.logStuff,
  { message: "daily cron" },
);

// Register a cron to run every hour.
const hourly = await crons.register(
  ctx,
  { kind: "interval", ms: 3600000 },
  internal.example.logStuff,
  { message: "hourly cron" },
);
```

它支持间隔( 毫秒) 以及相同的克龙时间表 格式为 unix `cron` 命令 :

```
 *  *  *  *  *  *
 ┬  ┬  ┬  ┬  ┬  ┬
 │  │  │  │  │  |
 │  │  │  │  │  └── day of week (0 - 7, 1L - 7L) (0 or 7 is Sun)
 │  │  │  │  └───── month (1 - 12)
 │  │  │  └──────── day of month (1 - 31, L)
 │  │  └─────────── hour (0 - 23)
 │  └────────────── minute (0 - 59)
 └───────────────── second (0 - 59, optional)
```

### 设计

这个组件的设计是基于Cronvex的演示应用 描述 内 [此堆栈帖](https://stack.convex.dev/cron-jobs)。 。 。 .

## 预先要求: Convex

你需要一个现有的 Convex 项目来使用组件。 Convex 是一个主机 后端平台,包括数据库、无服务器功能和多一个吨 可以学习 [这里](https://docs.convex.dev/get-started)。 。 。 .

运行 `npm create convex` 或遵循其中任何一条 [快速启动](https://docs.convex.dev/home) 来设置一个.

## 安装

安装组件包 :

```ts
npm install @convex-dev/crons
```

创建一个 `convex.config.ts` 应用程序中的文件 `convex/` 文件夹并安装 通过调用 `use`数字 :

```ts
// convex/convex.config.ts
import { defineApp } from "convex/server";
import crons from "@convex-dev/crons/convex.config.js";

const app = defineApp();
app.use(crons);

export default app;
```

## 使用量

A 类 `Crons` 包装器可以在您的 Convex 代码中被即时化为:

```ts
import { components } from "./_generated/api";
import { Crons } from "@convex-dev/crons";

const crons = new Crons(components.crons);
```

这个 `Crons` 包装类提供下列方法:

-   `register(ctx, schedule, fn, args, name?)`: 注册新的 crun 工作.
-   `get(ctx, { name | id })`:通过姓名或身份证获得工作.
-   `list(ctx)`:列出所有 cron 任务.
-   `delete(ctx, { name | id })`:按名称或身份删除 cron 任务.

示例用法:

```ts
import { v } from "convex/values";
import { internalMutation } from "./_generated/server";
import { internal } from "./_generated/api";

// Dummy function that we're going to schedule.
export const logStuff = internalMutation({
  args: {
    message: v.string(),
  },
  handler: async (_ctx, args) => {
    console.log(args.message);
  },
});

// Run a bunch of cron operations as a test. Note that this function runs as a
// transaction and cleans up after itself so you won't actually see these crons
// showing up in the database while it's in progress.
export const doSomeStuff = internalMutation({
  handler: async (ctx) => {
    // Register some crons.
    const namedCronId = await crons.register(
      ctx,
      { kind: "interval", ms: 3600000 },
      internal.example.logStuff,
      { message: "Hourly cron test" },
      "hourly-test",
    );
    console.log("Registered new cron job with ID:", namedCronId);
    const unnamedCronId = await crons.register(
      ctx,
      { kind: "cron", cronspec: "0 * * * *" },
      internal.example.logStuff,
      { message: "Minutely cron test" },
    );
    console.log("Registered new cron job with ID:", unnamedCronId);

    // Get the cron job by name.
    const cronByName = await crons.get(ctx, { name: "hourly-test" });
    console.log("Retrieved cron job by name:", cronByName);

    // Get the cron job by ID.
    const cronById = await crons.get(ctx, { id: unnamedCronId });
    console.log("Retrieved cron job by ID:", cronById);

    // List all cron jobs.
    const allCrons = await crons.list(ctx);
    console.log("All cron jobs:", allCrons);

    // Delete the cron jobs.
    await crons.delete(ctx, { name: "hourly-test" });
    console.log("Deleted cron job by name:", "hourly-test");
    await crons.delete(ctx, { id: unnamedCronId });
    console.log("Deleted cron job by ID:", unnamedCronId);

    // Verify deletion.
    const deletedCronByName = await crons.get(ctx, { name: "hourly-test" });
    console.log("Deleted cron job (should be null):", deletedCronByName);
    const deletedCronById = await crons.get(ctx, { id: unnamedCronId });
    console.log("Deleted cron job (should be null):", deletedCronById);
  },
});
```

如果你想静静地定义 衣着工作像内置 `crons.ts` Convex 特性,您可以通过 imit 脚本来进行 冠以给定的名字。 例如,在 `init.ts` 每次部署都会运行的文件 通过 `convex dev --run init`。 。 。 .

```ts
// Register a daily cron job. This could be called from an init script to make
// sure it's always registered, like the built-in crons in Convex.
export const registerDailyCron = internalMutation({
  handler: async (ctx) => {
    if ((await crons.get(ctx, { name: "daily" })) === null) {
      await crons.register(
        ctx,
        { kind: "cron", cronspec: "0 0 * * *" },
        internal.example.logStuff,
        {
          message: "daily cron",
        },
        "daily",
      );
    }
  },
});
```

Crons 是以交易方式创建的,并保证在 产生它们的突变已经运行。 这样可以写工作流程 然后在运行时立即删除, 没有其它关于 cron 不存在的错误处理.

```ts
// This will schedule a cron job to run every 10 seconds but then delete itself
// the first time it runs.
export const selfDeletingCron = internalMutation({
  handler: async (ctx) => {
    const cronId = await crons.register(
      ctx,
      { kind: "interval", ms: 10000 },
      internal.example.deleteSelf,
      { name: "self-deleting-cron" },
      "self-deleting-cron",
    );

    console.log("Registered self-deleting cron job with ID:", cronId);
  },
});

// Worker function that deletes a cron job.
export const deleteSelf = internalMutation({
  args: { name: v.string() },
  handler: async (ctx, { name }) => {
    console.log("Self-deleting cron job running. Name:", name);
    await crons.delete(ctx, { name });
    console.log("Self-deleting cron job has been deleted. Name:", name);
  },
});
```

## 常见问题

### @convex-dev/crons 是什么？

用于定期工作调度的对流组件 \.

### 如何安装 @convex-dev/crons？

在项目目录运行 npm install @convex-dev/crons，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：convex（^1\.24\.8）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

### @convex-dev/crons 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @convex-dev/crons 支持 ESM 还是 CommonJS？

以 ES Module 形式发布，推荐使用 import 引入。在 CommonJS 项目中，Node\.js 20\.19\+ / 22\.12\+ 可以直接 require\(\) 不含顶层 await 的 ES Module，更早的版本需要改用动态 import\(\)。

### @convex-dev/crons 可以商用吗？

@convex-dev/crons 使用 Apache-2\.0 许可。宽松许可：允许商业使用、修改和再分发，并附带明确的专利授权；分发时需保留许可与 NOTICE 文件，修改过的文件要注明改动。以上为概括，不构成法律意见，请以许可原文为准。

### @convex-dev/crons 的下载量有多少？

根据 npm 官方下载统计，@convex-dev/crons 在 2026/10/11 – 2026/11/09 这 30 天内被下载 357,125 次，日均约 11,904 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @convex-dev/crons 还在维护吗？

最新版本 0\.2\.3 发布于 2026/10/10（1 个月前）；至今共发布 18 个版本，其中过去 12 个月发布了 4 个；首次发布于 2024/09/20。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

