Guide

任务


¥Tasks

Nitro 任务允许在运行时进行开关操作。

选择加入实验性功能

¥Opt-in to the experimental feature

任务支持目前处于实验阶段。相关讨论请参阅 nitrojs/nitro#1974

为了使用任务 API,你需要启用实验性功能标志。

¥In order to use the tasks API you need to enable experimental feature flag.

export default defineNitroConfig({
  experimental: {
    tasks: true
  }
})

定义任务

¥Define tasks

任务可以在 server/tasks/[name].ts 文件中定义。

¥Tasks can be defined in server/tasks/[name].ts files.

嵌套目录支持。任务名称将与 : 连接。(例如:server/tasks/db/migrate.ts 任务名称将为 db:migrate

¥Nested directories are supported. The task name will be joined with :. (Example: server/tasks/db/migrate.tstask name will be db:migrate)

示例:

¥Example:

server/tasks/db/migrate.ts
export default defineTask({
  meta: {
    name: "db:migrate",
    description: "Run database migrations",
  },
  run({ payload, context }) {
    console.log("Running DB migration task...");
    return { result: "Success" };
  },
});

已调度任务

¥Scheduled tasks

你可以使用 Nitro 配置定义计划任务,使其在每个时间段后自动运行。

¥You can define scheduled tasks using Nitro configuration to automatically run after each period of time.

export default defineNitroConfig({
  scheduledTasks: {
    // Run `cms:update` task every minute
    '* * * * *': ['cms:update']
  }
})
你可以使用 crontab.guru 轻松生成和理解 cron tab 模式。

平台支持

¥Platform support

  • croner 引擎支持 devnode-serverbundeno-server 预设。
  • cloudflare_module 预设与 Cron 触发器 原生集成。确保将 wrangler 配置为使用与 scheduledTasks 中定义的完全相同的模式进行匹配。
  • 计划支持更多预设(包含原生原语支持)!

以编程方式运行任务

¥Programmatically run tasks

要手动运行任务,你可以使用 runTask(name, { payload? }) 工具。

¥To manually run tasks, you can use runTask(name, { payload? }) utility.

示例:

¥Example:

server/api/migrate.ts
export default eventHandler(async (event) => {
  // IMPORTANT: Authenticate user and validate payload!
  const payload = { ...getQuery(event) };
  const { result } = await runTask("db:migrate", { payload });

  return { result };
});

使用开发服务器运行任务

¥Run tasks with dev server

Nitro 内置的开发服务器公开了无需编程即可轻松执行的任务。

¥Nitro's built-in dev server exposes tasks to be easily executed without programmatic usage.

使用 API 路由

¥Using API routes

/_nitro/tasks

此端点返回可用任务名称及其元数据的列表。

¥This endpoint returns a list of available task names and their meta.

// [GET] /_nitro/tasks
{
  "tasks": {
    "db:migrate": {
      "description": "Run database migrations"
    },
     "cms:update": {
      "description": "Update CMS content"
    }
  },
  "scheduledTasks": [
    {
      "cron": "* * * * *",
      "tasks": [
        "cms:update"
      ]
    }
  ]
}

/_nitro/tasks/:name

此端点执行一项任务。你可以使用查询参数和正文 JSON 负载来提供负载。JSON 主体有效负载中发送的有效负载必须位于 "payload" 属性下。

¥This endpoint executes a task. You can provide a payload using both query parameters and body JSON payload. The payload sent in the JSON body payload must be under the "payload" property.

export default defineTask({
  meta: {
    name: "echo:payload",
    description: "Returns the provided payload",
  },
  run({ payload, context }) {
    console.log("Running echo task...");
    return { result: payload };
  },
});
主体中包含的 JSON 有效负载将覆盖查询参数中存在的键。

使用 CLI

¥Using CLI

这些命令只能在开发服务器运行时运行。你应该在另一个终端中运行它们。

列出任务

¥List tasks

nitro task list

运行任务

¥Run a task

nitro task run db:migrate --payload "{}"

备注

¥Notes

并发性

¥Concurrency

每个任务可以有一个正在运行的实例。并行多次调用同名任务,最终只会调用一次,并且所有调用者都将获得相同的返回值。

¥Each task can have one running instance. Calling a task of same name multiple times in parallel, results in calling it once and all callers will get the same return value.

Nitro 任务可以多次并行运行。