Tasks: Overview
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, scheduled tasks, zod tasks and webhook tasks.
Hello world task and how to trigger it
Here’s an incredibly simple task:
You can trigger this in two ways:
- From the dashboard using the “Test” feature.
- Trigger it from your backend code. See the full triggering guide here.
Here’s how to trigger a single run from elsewhere in your code:
You can also trigger a task from another task, 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. It’s an async function that has two arguments:
- The run payload - the data that you pass to the task when you trigger it.
- An object with
ctx
about the run (Context), and any output from the optionalinit
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:
For more information read the retrying guide, or see the SDK reference.
It’s also worth mentioning that you can retry a block of code 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.
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.
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.
onSuccess
function
When a task attempt succeeds, the onSuccess
function is called. It’s useful for sending notifications, logging, or other side effects.
onError
function
When a task attempt fails, the onError
function is called. It’s useful for sending notifications, logging, or other side effects.
Next steps
Was this page helpful?