Skip to content

Task

Workload for tasks (an operation or a job) that can be executed asynchronously.

Description

With this workload, you can define tasks for your application, such as:

  • Sending emails.
  • Dispatching notifications.
  • Generating reports.

Tasks can be performed immediately or enqueued (backed by Redis or AWS SQS).

A Task is initialized with a unique name, a function to process the task, and the following options:

You can provide a type parameter for the expected payload to use when sending and processing a task.

ts
import { Task } from "@monolayer/sdk";

const confirmationEmail = new Task<{ email: string }>(
  "sendConfirmationEmail",
  async ({ taskId, data }) => {
    await mailer.client.sendMail({
      from: "sender@example.com",
      to: data.email,
      subject: "Message in a bottle",
      text: "I hope this message gets there!",
    });
  },
  {
    retry: {
      times: 3,
    },
    onError: (error) => {},
  }
);

export default confirmationEmail;

Important

Export only one Task workload per file as the default export.

Tasks can be performed immediately with performNow or enqueued with performLater.

ts
// Perform a task immediately
confirmationEmail.performNow({ email: "text@example.com" })

// Enqueue a task
confirmationEmail.performLater({ email: "text@example.com" })
confirmationEmail.performLater({ email: "text@example.com" }, { delay: 1000 });

Development environment

Tasks are executed immediately.

Test environment

Enqueued tasks with performLater will be collected in the test environment.

You can inspect the collected tasks with the enqueuedTasks test helper.