Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions docs/1.guide/10.tasks.md
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,24 @@ export default eventHandler(async (event) => {
});
```

## Scheduled one time tasks

To run a scheduled task once in the future, you can use `runTask(name, { context: { waitFor: 10 }})` to run the task in 10 seconds.

**Example:**

```ts [server/api/runOnce.ts]
export default eventHandler(async (event) => {
runTask("future", { payload, context: { waitFor: 10 } });

return { result: "Scheduled to run in 10 seconds" };
});
```

> [!IMPORTANT]
> Scheduled one time tasks are only ever run on full seconds.
> If the actual time would be `YYYY-MM-DD HH:MM:10.250`, the task will be run on `YYYY-MM-DD HH:MM:11`.

## Run tasks with dev server

Nitro's built-in dev server exposes tasks to be easily executed without programmatic usage.
Expand Down
13 changes: 9 additions & 4 deletions src/presets/_nitro/runtime/nitro-dev.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,13 +74,18 @@ nitroApp.router.use(
"/_nitro/tasks/:name",
defineEventHandler(async (event) => {
const name = getRouterParam(event, "name") as string;
const body: any = await readBody(event);

const payload = {
...getQuery(event),
...(await readBody(event)
.then((r) => r?.payload)
.catch(() => ({}))),
...(body && typeof body === "object" ? body.payload : {}),
};

const context = {
...(body && typeof body === "object" ? body.context : {}),
};
return await runTask(name, { payload });

return await runTask(name, { payload, context });
})
);

Expand Down
43 changes: 36 additions & 7 deletions src/runtime/internal/task.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,9 @@ export async function runTask<RT = unknown>(
context = {},
}: { payload?: TaskPayload; context?: TaskContext } = {}
): Promise<TaskResult<RT>> {
if (__runningTasks__[name]) {
const runImmediately = !context?.waitFor;

if (!runImmediately && __runningTasks__[name]) {
return __runningTasks__[name];
}

Expand All @@ -50,14 +52,41 @@ export async function runTask<RT = unknown>(

const handler = (await tasks[name].resolve!()) as Task<RT>;
const taskEvent: TaskEvent = { name, payload, context };
__runningTasks__[name] = handler.run(taskEvent);

try {
const res = await __runningTasks__[name];
return res;
} finally {
delete __runningTasks__[name];
if (runImmediately) {
__runningTasks__[name] = handler.run(taskEvent);
try {
const res = await __runningTasks__[name];
return res;
} finally {
delete __runningTasks__[name];
}
}

const nextExecution = new Date();
nextExecution.setSeconds(nextExecution.getSeconds() + context.waitFor!);

const p = new Promise<TaskResult<RT>>((resolve, reject) => {
const job = new Cron(
"* * * * * *",
async () => {
try {
const res = await handler.run(taskEvent);
resolve(res);
} catch (error) {
reject(error);
} finally {
job.stop();
}
},
{
startAt: nextExecution,
maxRuns: 1,
}
);
});

return p;
}

/** @experimental */
Expand Down
9 changes: 8 additions & 1 deletion src/types/runtime/task.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,14 @@
type MaybePromise<T> = T | Promise<T>;

/** @experimental */
export interface TaskContext {}
export interface TaskContext {
/**
* Amount of time in seconds to wait before running the task.
* Task runs on the next full second after the specified wait time.
* 0 is treated as no wait time.
*/
waitFor?: number;
}

/** @experimental */
export interface TaskPayload {
Expand Down
16 changes: 16 additions & 0 deletions test/fixture/routes/tasks/oneTimeTask.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
export default eventHandler(async (event) => {
const current = new Date();

await runTask("echo", {
context: {
waitFor: 1,
},
});

const after = new Date();

return {
current: current.toISOString(),
after: after.toISOString(),
};
});
8 changes: 8 additions & 0 deletions test/fixture/tasks/echo.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
export default defineTask({
meta: {
name: "echo",
},
async run({ payload, context }) {
return { payload, context };
},
});
55 changes: 53 additions & 2 deletions test/presets/nitro-dev.test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,16 @@
import type { OpenAPI3 } from "openapi-typescript";
import { describe, expect, it } from "vitest";
import { describe, expect, it, vi } from "vitest";
import { setupTest, testNitro } from "../tests";
import type test from "node:test";

describe("nitro:preset:nitro-dev", async () => {
const ctx = await setupTest("nitro-dev");
const ctx = await setupTest("nitro-dev", {
config: {
experimental: {
tasks: true,
},
},
});
testNitro(
ctx,
() => {
Expand Down Expand Up @@ -69,6 +76,50 @@ describe("nitro:preset:nitro-dev", async () => {
`);
});
});

describe("tasks", () => {
it("should get the defined tasks", async () => {
const res = await callHandler({ url: "/_nitro/tasks" });

expect(res.data).toEqual({
scheduledTasks: [
{
cron: "* * * * *",
tasks: ["test"],
},
],
tasks: {
"db:migrate": {
description: "Run database migrations",
},
"db:seed": {},
test: {
description: "task to debug",
},
echo: {},
},
});
});

it("should run a scheduled task", async () => {
const res = await callHandler({
url: "/tasks/oneTimeTask",
});

// now extract current and after from the response
const { current, after } = res.data;

// convert the dates to Date objects
const currentD = new Date(current);
const afterD = new Date(after);

// calculate the difference in seconds
const diff = (afterD.getTime() - currentD.getTime()) / 1000;

// expect the difference to be more than 1 seconds as croner runs on the next full second
expect(diff).toBeGreaterThan(1);
});
});
}
);
});