Files
triggerdotdev--trigger.dev/docs/v3/tasks-overview.mdx
T
Matt Aitken de302858f8 v3 docs (#929)
* Started building out the docs navigation

* Drafted out a lot of the docs pages. With just titles and descriptions with a coming soon message for now.

* A ton more scaffolded pages with titles, descriptions, coming soon/incomplete docs messages

* Created the remaining page stubs

* Introduction page improvements

* Lots of docs changes, mostly the task overview page

* Moved some bits around

* Task overview fleshed out

* Triggering docs page

* Regular task page

* CLi dev docs

* Docs for debugging locally

* Environment variables docs

* Added env var images

* Deployment guides

* Updated the title of “Integrations” to “Deployment integrations” to make it less confusing

* Lots more docs pages

* Changed the language to JavaScript

* Fixed typos about queues and added a simple code sample

* Moved the local debugger docs into the CLI dev page

* Added the CLI deploy options

* Delete the local debugger page

* Updated the logging page with structured logging

* Added the new CLI deploy options

* Change to h4 for one of the options

* Errors page

* WIP on retrying

* Retrying guide

* Wait docs pages

* Queuing docs simplified, partial written

* Queuing and concurrency docs

* Run tests docs

* New combined error and retrying page

* Errors and retrying page updated

* More docs

* Added a possible configurations coming soon table

* Created a limits page

* Added warnings about how you need to get early access

* Minor fixes for the docs
2024-03-22 14:09:27 +00:00

156 lines
4.9 KiB
Plaintext
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
---
title: "Tasks: Overview"
sidebarTitle: "Tasks"
description: "Tasks are functions that can run for a long time and provide strong resilience to failure."
---
There are different types of tasks including [regular tasks](/v3/tasks-regular), [scheduled tasks](/v3/tasks-scheduled), [zod tasks](/v3/tasks-zod) and [webhook tasks](/v3/tasks-webhooks).
## Hello world task and how to trigger it
Here's an incredibly simple task:
```ts /trigger/hello-world.ts
import { task } from "@trigger.dev/sdk/v3";
//1. You need to export each task
export const helloWorld = task({
//2. Use a unique id for each task
id: "hello-world",
//3. The run function is the main function of the task
run: async (payload: { message: string }) => {
//4. You can write code that runs for a long time here, there are no timeouts
console.log(payload.message);
},
});
```
You can trigger this in two ways:
1. From the dashboard [using the "Test" feature](/v3/develop-run-tests).
2. Trigger it from your backend code. See the [full triggering guide here](/v3/triggering).
Here's how to trigger a single run from elsewhere in your code:
```ts Your backend code
import { helloWorldTask } from "./trigger/hello-world";
async function triggerHelloWorld() {
//This triggers the task and return a handle
const handle = await helloWorld.trigger({ payload: { message: "Hello world!" } });
//You can use the handle to check the status of the task, cancel and retry it.
console.log("Task is running with handle", handle.id);
}
```
You can also [trigger a task from another task](/v3/triggering), and wait for the result.
## Defining a `task`
The task function takes an object with the following fields.
### The `id` field
This is used to identify your task so it can be triggered, managed, and you can view runs in the dashboard. This must be unique in your project we recommend making it descriptive and unique.
### The `run` function
Your custom code inside `run()` will be executed when your task is triggered. Its an async function that has two arguments:
1. The run payload - the data that you pass to the task when you trigger it.
2. An object with `ctx` about the run ([Context](/v3/reference-context)), and any output from the optional `init` function that runs before every run attempt.
Anything you return from the `run` function will be the result of the task. Data you return must be JSON serializable: strings, numbers, booleans, arrays, objects, and null.
### `retry` options
A task is retried if an error is thrown, by default we retry 3 times.
You can set the number of retries and the delay between retries in the `retry` field:
```ts /trigger/retry.ts
export const taskWithRetries = task({
id: "task-with-retries",
retry: {
maxAttempts: 10,
factor: 1.8,
minTimeoutInMs: 500,
maxTimeoutInMs: 30_000,
randomize: false,
},
run: async ({ payload, ctx }) => {
//...
},
});
```
For more information read [the retrying guide](/v3/retrying), or see the [SDK reference](/v3/reference-task).
It's also worth mentioning that you can [retry a block of code](/v3/retrying) inside your tasks as well.
### `queue` options
Queues allow you to control the concurrency of your tasks. This allows you to have one-at-a-time execution and parallel executions. There are also more advanced techniques like having different concurrencies for different sets of your users. For more information read [the concurrency & queues guide](/v3/queue-concurrency).
```ts /trigger/one-at-a-time.ts
export const oneAtATime = task({
id: "one-at-a-time",
queue: {
concurrencyLimit: 1,
},
run: async ({ payload, ctx }) => {
//...
},
});
```
### `machine` options
Some tasks require more vCPUs or GBs of RAM. You can specify these requirements in the `machine` field. For more information read [the machines guide](/v3/machines).
```ts /trigger/heavy-task.ts
export const heavyTask = task({
id: "heavy-task",
machine: {
cpu: 2,
memory: 4,
},
run: async ({ payload, ctx }) => {
//...
},
});
```
### `init` function
This function is called before a run attempt.
### `cleanup` function
This function is called after a run attempt has succeeded or failed.
### `middleware` function
This function is called before the `run` function, it allows you to wrap the run function with custom code. For more information [read the guide](/v3/middleware).
### `onSuccess` function
When a task attempt succeeds, the `onSuccess` function is called. It's useful for sending notifications, logging, or other side effects.
<Snippet file="coming-soon-slim.mdx" />
### `onError` function
When a task attempt fails, the `onError` function is called. It's useful for sending notifications, logging, or other side effects.
<Snippet file="coming-soon-slim.mdx" />
## Next steps
<CardGroup>
<Card title="Writing tasks" icon="wand-magic-sparkles" href="/v3/writing-tasks-introduction">
Tasks are the core of Trigger.dev. Learn how to write them.
</Card>
</CardGroup>