# Schedule, cancel and reschedule tasks

> Schedule delayed tasks with pushq using delay_seconds or schedule_time, then cancel or reschedule them by task ID. Includes a follow-up reminder example.

Source: https://pushqueue.dev/docs/patterns/scheduling-and-cancelling/

This pattern covers delayed and scheduled tasks in pushq: sending a request later (a reminder, a follow-up email, a trial-expiry check), cancelling it when it is no longer needed, and moving it to a different time. You give each scheduled task a predictable task ID, so you can cancel it later without storing anything.

## Schedule a follow-up and cancel it

A user signs up. If they haven't activated in three days, send a follow-up email. If they activate before then, cancel it.


**TypeScript**

```ts

// At signup: follow up in 3 days.
await pq.createTask("emails", {
  taskId: "followup-user-42",
  path: "/hooks/follow-up",
  jsonBody: { userId: 42 },
  delaySeconds: 3 * 24 * 3600,
});

// When the user activates: cancel it.
try {
  await pq.deleteTask("emails", "followup-user-42");
} catch (err) {
  if (!(err instanceof PushqError && err.code === "not_found")) throw err; // already cancelled
}
```

**Python**

```python
from pushq import PushqError

# At signup: follow up in 3 days.
pq.create_task(
    "emails",
    task_id="followup-user-42",
    path="/hooks/follow-up",
    json_body={"user_id": 42},
    delay_seconds=3 * 24 * 3600,
)

# When the user activates: cancel it.
try:
    pq.delete_task("emails", "followup-user-42")
except PushqError as e:
    if e.code != "not_found":  # not_found: already cancelled
        raise
```

**Go**

```go
// At signup: follow up in 3 days.
_, err := pq.CreateTask(ctx, "emails", pushq.TaskCreate{
	TaskID:       "followup-user-42",
	Path:         "/hooks/follow-up",
	JSONBody:     map[string]any{"user_id": 42},
	DelaySeconds: pushq.Float64(3 * 24 * 3600),
})
if err != nil {
	return err
}

// When the user activates: cancel it. not_found means it was already cancelled.
if err := pq.DeleteTask(ctx, "emails", "followup-user-42"); err != nil && !pushq.IsCode(err, "not_found") {
	return err
}
```

**Java**

```java
// At signup: follow up in 3 days.
pq.createTask("emails", TaskCreate.builder()
    .taskId("followup-user-42")
    .path("/hooks/follow-up")
    .jsonBody(Map.of("user_id", 42))
    .delaySeconds(3 * 24 * 3600)
    .build());

// When the user activates: cancel it.
try {
    pq.deleteTask("emails", "followup-user-42");
} catch (PushqException e) {
    if (!"not_found".equals(e.getCode())) throw e; // not_found: already cancelled
}
```

**.NET**

```csharp
// At signup: follow up in 3 days.
await pq.CreateTaskAsync("emails", new TaskCreate
{
    TaskId = "followup-user-42",
    Path = "/hooks/follow-up",
    JsonBody = new { user_id = 42 },
    Delay = TimeSpan.FromDays(3),
});

// When the user activates: cancel it.
try
{
    await pq.DeleteTaskAsync("emails", "followup-user-42");
}
catch (PushqException e) when (e.Code == "not_found")
{
    // already cancelled
}
```

**curl**

```bash
# At signup: follow up in 3 days (259200 seconds).
curl -X POST https://api.pushqueue.dev/v1/queues/emails/tasks \
  -H "Authorization: Bearer $PUSHQ_API_KEY" -H "Content-Type: application/json" \
  -d '{"task_id":"followup-user-42","path":"/hooks/follow-up","json_body":{"user_id":42},"delay_seconds":259200}'

# When the user activates: cancel it (204 No Content; 404 not_found if already cancelled).
curl -X DELETE https://api.pushqueue.dev/v1/queues/emails/tasks/followup-user-42 \
  -H "Authorization: Bearer $PUSHQ_API_KEY"
```

The examples assume a client named `pq` (see [install and configure an SDK](https://pushqueue.dev/docs/getting-started/sdks/)). The text uses JSON field names; the SDKs use their language's casing (`delaySeconds` in TypeScript and Java, `delay_seconds` in Python, `DelaySeconds` in Go, and a `TimeSpan` named `Delay` in .NET).

Use this when something should happen later unless something else happens first: reminders, follow-ups, abandoned-cart nudges, trial-expiry checks, "close this ticket if no reply in 7 days".

A deterministic task ID (`followup-user-42`) does double duty: it makes enqueueing [idempotent](https://pushqueue.dev/docs/concepts/tasks/#task-ids-and-deduplication) (a second create for the same user returns `already_exists` instead of a second follow-up), and it lets you cancel the task from anywhere that knows the user ID.

## Delay a task or schedule it at an exact time

Set one of these on the task, not both (sending both is `invalid_argument`):

| Parameter | Type | Default | Description |
| --- | --- | --- | --- |
| `delay_seconds` | number | `0` | Deliver this many seconds after the task is created. Must be `>= 0`; fractions are allowed. |
| `schedule_time` | string (RFC 3339) | now | Deliver at this instant, for example `2026-12-01T09:00:00Z`. A time in the past makes the task due immediately. |

Use `delay_seconds` for relative times ("in 3 days") and `schedule_time` for wall-clock times ("Monday 09:00 in the user's time zone"). `schedule_time` is an absolute instant: convert the user's local time to UTC (or include the offset) in your code.


**TypeScript**

```ts
await pq.createTask("emails", {
  taskId: "digest-user-42-2026-12-07",
  path: "/hooks/weekly-digest",
  jsonBody: { userId: 42 },
  scheduleTime: new Date("2026-12-07T09:00:00-05:00"), // 09:00 New York time
});
```

**Python**

```python
from datetime import datetime, timedelta, timezone

pq.create_task(
    "emails",
    task_id="digest-user-42-2026-12-07",
    path="/hooks/weekly-digest",
    json_body={"user_id": 42},
    schedule_time=datetime(2026, 12, 7, 9, 0, tzinfo=timezone(timedelta(hours=-5))),  # 09:00 New York
)
```

**Go**

```go
ny, _ := time.LoadLocation("America/New_York")
at := time.Date(2026, 12, 7, 9, 0, 0, 0, ny)
_, err := pq.CreateTask(ctx, "emails", pushq.TaskCreate{
	TaskID:       "digest-user-42-2026-12-07",
	Path:         "/hooks/weekly-digest",
	JSONBody:     map[string]any{"user_id": 42},
	ScheduleTime: &at, // sent as UTC
})
```

**Java**

```java
Instant at = ZonedDateTime.of(2026, 12, 7, 9, 0, 0, 0, ZoneId.of("America/New_York")).toInstant();
pq.createTask("emails", TaskCreate.builder()
    .taskId("digest-user-42-2026-12-07")
    .path("/hooks/weekly-digest")
    .jsonBody(Map.of("user_id", 42))
    .scheduleTime(at)
    .build());
```

**.NET**

```csharp
await pq.CreateTaskAsync("emails", new TaskCreate
{
    TaskId = "digest-user-42-2026-12-07",
    Path = "/hooks/weekly-digest",
    JsonBody = new { user_id = 42 },
    ScheduleTime = new DateTimeOffset(2026, 12, 7, 9, 0, 0, TimeSpan.FromHours(-5)), // 09:00 New York
});
```

**curl**

```bash
curl -X POST https://api.pushqueue.dev/v1/queues/emails/tasks \
  -H "Authorization: Bearer $PUSHQ_API_KEY" -H "Content-Type: application/json" \
  -d '{"task_id":"digest-user-42-2026-12-07","path":"/hooks/weekly-digest",
       "json_body":{"user_id":42},"schedule_time":"2026-12-07T09:00:00-05:00"}'
```

## How far ahead you can schedule a task

A task can be scheduled at most **one year** ahead on a default self-hosted server (`limits.max_schedule_ahead`, or `PUSHQ_MAX_SCHEDULE_AHEAD`; see [self-hosting configuration](https://pushqueue.dev/docs/self-hosting/configuration/)). The limit applies to both `delay_seconds` and `schedule_time`; going past it returns `invalid_argument` with "schedule_time is more than ... ahead". Independently of that setting, `delay_seconds` can never exceed 100 years.

For anything further out (a renewal reminder in two years), store the date in your own database and have a periodic job enqueue the task once it is within range.

## Cancel a scheduled task by ID

Delete the task with `DELETE /v1/queues/{queue}/tasks/{task_id}`. What that does depends on where the task is:

| Task state | Effect of delete |
| --- | --- |
| `pending` (waiting for its time, or due) | Removed. It is never delivered. |
| `running` (a request is in flight) | Marked deleted and its result is discarded, so it won't be retried. The request already sent can't be recalled. |
| `succeeded` or `failed` | The record is removed. Delivery already happened (or gave up). |
| Already deleted, or never existed | `404 not_found`. |

To cancel every scheduled task for a user, give their tasks a shared prefix (`followup-user-42`, `digest-user-42-2026-12-07`, ...) and delete the pending ones you find with `id_prefix`:


**TypeScript**

```ts
const page = await pq.listTasks("emails", { state: "pending", idPrefix: "digest-user-42-", pageSize: 1000 });
for (const t of page.items) await pq.deleteTask("emails", t.id);
```

**Python**

```python
page = pq.list_tasks("emails", state="pending", id_prefix="digest-user-42-", page_size=1000)
for t in page.items:
    pq.delete_task("emails", t.id)
```

**Go**

```go
tasks, _, err := pq.ListTasks(ctx, "emails", pushq.ListTasksParams{
	State: "pending", IDPrefix: "digest-user-42-", PageSize: 1000,
})
if err != nil {
	return err
}
for _, t := range tasks {
	if err := pq.DeleteTask(ctx, "emails", t.ID); err != nil && !pushq.IsCode(err, "not_found") {
		return err
	}
}
```

**Java**

```java
TaskPage page = pq.listTasks("emails", ListTasksParams.builder()
    .state("pending").idPrefix("digest-user-42-").pageSize(1000).build());
for (Task t : page.getTasks()) {
    pq.deleteTask("emails", t.getId());
}
```

**.NET**

```csharp
var page = await pq.ListTasksAsync("emails", new ListTasksOptions
{
    State = TaskState.Pending, IdPrefix = "digest-user-42-", PageSize = 1000,
});
foreach (var t in page.Items) await pq.DeleteTaskAsync("emails", t.Id);
```

**curl**

```bash
curl "https://api.pushqueue.dev/v1/queues/emails/tasks?state=pending&id_prefix=digest-user-42-&page_size=1000" \
  -H "Authorization: Bearer $PUSHQ_API_KEY"
# then DELETE /v1/queues/emails/tasks/<id> for each task in the response
```

If a user can have more than 1,000 pending tasks, follow `next_page_token` as shown in [list and filter tasks](https://pushqueue.dev/docs/concepts/tasks/#list-and-filter-tasks).

:::caution[Cancel and delivery can race]
If the task becomes due while you are deleting it, it may already be in flight. Make the handler check whether the work is still wanted (has the user activated?) and answer `2xx` without acting if not. That check is what makes cancellation reliable; the delete is an optimization. See [idempotent handlers](https://pushqueue.dev/docs/patterns/idempotent-handlers/).
:::

## Reschedule a task

pushq has no "update task" call. To move a task to a new time, delete it and create it again.

:::caution[A deleted task ID stays reserved]
After a delete, the task ID is kept as a tombstone for the dedup window (1 hour on a default self-hosted server, `limits.dedup_window`). Creating a task with the same ID in that window fails with `already_exists`. IDs of finished tasks are reserved even longer: for their retention period (24 hours after success, 7 days after failure, by default). See [task IDs and deduplication](https://pushqueue.dev/docs/concepts/tasks/#task-ids-and-deduplication).
:::

So give the new task a new ID. A version or the target time in the ID works well, and an `id_prefix` lookup still finds it:


**TypeScript**

```ts
// Move the follow-up from 3 days to 7 days after signup.
await pq.deleteTask("emails", "followup-user-42");
await pq.createTask("emails", {
  taskId: "followup-user-42-v2",
  path: "/hooks/follow-up",
  jsonBody: { userId: 42 },
  delaySeconds: 7 * 24 * 3600,
});
```

**Python**

```python
# Move the follow-up from 3 days to 7 days after signup.
pq.delete_task("emails", "followup-user-42")
pq.create_task(
    "emails",
    task_id="followup-user-42-v2",
    path="/hooks/follow-up",
    json_body={"user_id": 42},
    delay_seconds=7 * 24 * 3600,
)
```

**Go**

```go
// Move the follow-up from 3 days to 7 days after signup.
if err := pq.DeleteTask(ctx, "emails", "followup-user-42"); err != nil && !pushq.IsCode(err, "not_found") {
	return err
}
_, err := pq.CreateTask(ctx, "emails", pushq.TaskCreate{
	TaskID:       "followup-user-42-v2",
	Path:         "/hooks/follow-up",
	JSONBody:     map[string]any{"user_id": 42},
	DelaySeconds: pushq.Float64(7 * 24 * 3600),
})
```

**Java**

```java
// Move the follow-up from 3 days to 7 days after signup.
pq.deleteTask("emails", "followup-user-42");
pq.createTask("emails", TaskCreate.builder()
    .taskId("followup-user-42-v2")
    .path("/hooks/follow-up")
    .jsonBody(Map.of("user_id", 42))
    .delaySeconds(7 * 24 * 3600)
    .build());
```

**.NET**

```csharp
// Move the follow-up from 3 days to 7 days after signup.
await pq.DeleteTaskAsync("emails", "followup-user-42");
await pq.CreateTaskAsync("emails", new TaskCreate
{
    TaskId = "followup-user-42-v2",
    Path = "/hooks/follow-up",
    JsonBody = new { user_id = 42 },
    Delay = TimeSpan.FromDays(7),
});
```

**curl**

```bash
curl -X DELETE https://api.pushqueue.dev/v1/queues/emails/tasks/followup-user-42 \
  -H "Authorization: Bearer $PUSHQ_API_KEY"
curl -X POST https://api.pushqueue.dev/v1/queues/emails/tasks \
  -H "Authorization: Bearer $PUSHQ_API_KEY" -H "Content-Type: application/json" \
  -d '{"task_id":"followup-user-42-v2","path":"/hooks/follow-up","json_body":{"user_id":42},"delay_seconds":604800}'
```

To cancel a rescheduled task later, look it up with `id_prefix: "followup-user-42"` rather than a fixed ID. Delete first, then create: if you create first and the delete fails, both versions are scheduled.

To move a pending task to **now**, use [run a task now](https://pushqueue.dev/docs/concepts/tasks/#run-a-task-now) (`POST .../tasks/{task_id}:run`) instead. It keeps the same ID, works only on pending tasks, and bypasses the queue's rate limit and paused state.

## How scheduled tasks are stored and delivered

A scheduled task is an ordinary `pending` task whose `schedule_time` is in the future. Nothing runs on your side while it waits. pushq's dispatcher tracks the earliest `schedule_time` of each queue and claims the task once that time has passed, subject to the queue's [rate limits](https://pushqueue.dev/docs/guides/rate-limits/). Queue stats count waiting tasks in `scheduled_future`, and each delivery carries the original time in the `X-Pushq-Scheduled-Time` header.

Some consequences:

- **Delivery is at or after `schedule_time`, not exactly at it.** A busy queue, a low rate limit, or a paused queue makes tasks late. Tasks that become due while a queue is paused go out when it is resumed.
- **Retries move the time.** If the first attempt fails, the task is retried with backoff (see [retries](https://pushqueue.dev/docs/concepts/retries/)), so the follow-up can arrive later than scheduled.
- **Scheduled tasks live in their queue.** Deleting or purging the queue removes every scheduled task in it.

## Pitfalls

- **Random task IDs.** Without a predictable ID you must store the returned ID to cancel the task later.
- **Reusing an ID right after delete.** It fails with `already_exists` for the dedup window; use a new ID.
- **Local times without an offset.** `schedule_time` must be an RFC 3339 instant. In Python a naive `datetime` is treated as UTC.
- **Relying on delete alone.** Re-check in the handler that the action is still wanted.
- **Scheduling years ahead.** Past the schedule-ahead limit the create fails; keep long-range dates in your own database.

## Read more

- [Tasks: delayed and scheduled tasks, IDs and states](https://pushqueue.dev/docs/concepts/tasks/)
- [Deduplicate tasks with task IDs](https://pushqueue.dev/docs/patterns/deduplication/)
- [Idempotent task handlers](https://pushqueue.dev/docs/patterns/idempotent-handlers/)
- [Bulk enqueue tasks in batches](https://pushqueue.dev/docs/patterns/bulk-enqueue/)
