---
title: "Vercel Schedules: Python SDK Reference"
description: "Reference for vercel-schedules: create, list, update, enable, disable, invoke, and delete schedules from Python, and read scheduled runs."
url: "https://vercel.com/docs/schedules/sdk/python"
last_updated: 2018-10-20
related:
  - /docs/schedules/sdk/javascript
  - /docs/cli/schedules
  - /docs/schedules/http-api
  - /docs/oidc
  - /docs/schedules/concepts
install_vercel_plugin: npx plugins add vercel/vercel-plugin
search_with_vercel_cli: npx vercel@latest docs search "<query>"
search_kb_with_vercel_cli: npx vercel@latest kb search "<query>"
---

# Vercel Schedules: Python SDK Reference

Use the [`vercel-schedules`](https://pypi.org/project/vercel-schedules/) package to create and manage dynamic schedules from Python, and to read runs in a function. For JavaScript and TypeScript, use the [JS SDK](/docs/schedules/sdk/javascript). To manage schedules from the terminal instead, use [`vercel schedules`](/docs/cli/schedules). To call the API without the SDK, see the [API Reference](/docs/schedules/http-api).

## Installation

The package requires Python 3.11 or later:

```bash
pip install vercel-schedules
```

Or with `uv`:

```bash
uv add vercel-schedules
```

## Authentication

On Vercel, the SDK authenticates with your deployment's [OIDC token](/docs/oidc). You don't need to configure anything. Each call applies to the environment or branch of the deployment that runs it:

| Code runs in | Calls apply to |
| --- | --- |
| A production deployment | Production schedules |
| A Preview deployment from Git | Schedules for that deployment's branch |
| A Preview deployment from the CLI | Schedules for [CLI deployments by the user who created it](/docs/schedules/concepts#environments) |
| A custom environment deployment | Schedules for that custom environment |
| `vercel dev` | The [local Schedules service](/docs/schedules/local-development) |

To run code outside Vercel and `vercel dev`, such as a script on your machine, run `vercel link` and `vercel env pull` so the SDK can read an OIDC token, or [pass a token](#configure-the-client).

## Async and sync functions

`vercel.schedules` exports async functions. `vercel.schedules.sync` exports the same functions, with the same names and arguments, for synchronous code:

```python
from vercel.schedules import get_schedule

schedule = await get_schedule("cleanup")
```

```python
from vercel.schedules.sync import get_schedule

schedule = get_schedule("cleanup")
```

The examples on this page use the async functions.

## Configure the client

To pass a token or a different API URL, open a session with `SchedulesServiceOptions`. Calls inside the session use these options:

```python
import os

from vercel.api import session
from vercel.schedules import (
    SchedulesServiceOptions,
    get_schedule,
    static_credentials_factory,
)

options = SchedulesServiceOptions(
    credentials_factory=static_credentials_factory(os.environ["SCHEDULES_TOKEN"]),
)

async with session(service_options=[options]):
    schedule = await get_schedule("cleanup")
```

| Option | Type | Description |
| --- | --- | --- |
| `credentials_factory` | Async callable that returns a `str` | Returns the token for each request, so it can return a refreshed token. `static_credentials_factory(token)` returns one that always uses `token`. Defaults to the deployment's OIDC token. |
| `base_url` | `str` | Schedules API URL. Defaults to the `VERCEL_SCHEDULE_BASE_URL` environment variable, or `https://vercel-schedules.com`. |
| `timeout` | `timedelta` | Positive HTTP timeout for each request. Defaults to 60 seconds. |

For synchronous code, import `SchedulesServiceOptions` and `static_credentials_factory` from `vercel.schedules.sync` and use a plain `with session(...)` block. Its `credentials_factory` is a regular function. You can't call async functions in a sync session, or the reverse.

## Create a schedule

`create_schedule()` creates a dynamic schedule that publishes to a [queue topic](/docs/schedules/handle-runs#queue-targets). It takes effect immediately.

```python
from datetime import timedelta

from vercel.schedules import Cron, create_schedule

schedule = await create_schedule(
    "cleanup",
    topic="scheduled-cleanup",
    cron=Cron(minute=0),  # every hour, on the hour
    timezone="America/New_York",
    jitter=timedelta(minutes=5),
    payload={"max_age_days": 30},
)

print(schedule.schedule_id, schedule.state)
```

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| `name` | `str` | Yes | Unique within the namespace. See [naming rules](/docs/schedules/configuration#schedule-names). |
| `topic` | `str` | Yes | Queue topic to publish to. Dynamic schedules only support queue topics. |
| `cron` | `Cron` or `str` | One of `cron` or `at` | When a recurring schedule runs, as a [`Cron`](#cron) or a crontab string such as `"0 * * * *"` |
| `at` | `datetime` | One of `cron` or `at` | When a [one-time schedule](#create-a-one-time-schedule) runs |
| `timezone` | `str` | No | IANA timezone for the expression. Defaults to `UTC`. |
| `namespace` | `str` | No | Groups schedules, for example by tenant. Defaults to `default`. |
| `jitter` | `timedelta` | No | [Jitter window](/docs/schedules/concepts#jitter) in whole minutes, from 1 to 15. On Hobby, omit it or pass 15 minutes. |
| `payload` | Any JSON value | No | JSON value, up to 16 KB, that Vercel includes in the `payload` field of each [queue message](/docs/schedules/handle-runs#queue-message-format). Passing `None` sets a JSON `null`. Omit it for no payload. |

Returns the new [`Schedule`](#schedule). Raises a `SchedulesApiError` with code `schedule_already_exists` if a schedule with the same name exists in the namespace. Raises a `SchedulesValidationError` before sending the request if the arguments are invalid, such as when you pass both `cron` and `at`.

### `Cron`

`Cron` builds a crontab expression from keyword arguments: `minute`, `hour`, `day`, `month`, and `day_of_week`, where `0` is Sunday. Each field takes a number or a crontab field string such as `"*/15"` or `"1-5"`.

Fields you leave out default to `*`, except fields less significant than every field you set, which default to their minimum. `day_of_week` always defaults to `*`:

| `Cron` | Crontab expression | Runs |
| --- | --- | --- |
| `Cron(minute=0)` | `0 * * * *` | Every hour |
| `Cron(hour=3)` | `0 3 * * *` | Every day at 03:00 |
| `Cron(hour=9, day_of_week="1-5")` | `0 9 * * 1-5` | Weekdays at 09:00 |
| `Cron(day=1)` | `0 0 1 * *` | Midnight on the first of each month |

`str(cron)` returns the crontab expression, and `Cron.from_crontab("0 3 * * *")` parses one. Month and weekday names aren't supported. See [Cron expressions](/docs/schedules/configuration#cron-expressions) for the full format rules.

### Create a one-time schedule

Pass `at` instead of `cron` to run once. An aware `datetime` with a `ZoneInfo` timezone, or UTC, sets the schedule's timezone itself:

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

await create_schedule(
    "send-reminder",
    topic="reminders",
    at=datetime(2027, 11, 1, 9, tzinfo=ZoneInfo("America/New_York")),
)

await create_schedule(
    "follow-up",
    topic="reminders",
    at=datetime.now(timezone.utc) + timedelta(hours=1),
)
```

- A naive `datetime` needs `timezone`.
- If you pass an aware `datetime` and `timezone`, the SDK converts `at` to that timezone. The schedule still runs at the same instant.
- One-time schedules have minute precision. The SDK rounds a time with seconds up to the next minute, so the schedule never runs before `at`.
- The SDK rejects fixed-offset timezones other than UTC unless you also pass `timezone`, because they don't have an IANA name.

See [One-time expressions](/docs/schedules/configuration#one-time-expressions) for the full format rules.

## List schedules

`query_schedules()` returns an async iterator over static and dynamic schedules in one namespace. It fetches the next page as you iterate:

```python
from vercel.schedules import query_schedules

async for schedule in query_schedules(namespace="default"):
    print(schedule.name, schedule.state, schedule.target)
```

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| `namespace` | `str` | No | Namespace to list. Defaults to `default`. |
| `page_size` | `int` | No | Schedules to fetch per request, from 1 to 100. Defaults to 20. |

With `vercel.schedules.sync`, `query_schedules()` returns a regular iterator, so use a `for` loop.

Static schedules can target a function or a path, so check the type of `target` before you read it:

```python
from vercel.schedules import FunctionTarget, PathTarget, QueueTarget, Schedule


def describe_target(schedule: Schedule) -> str:
    match schedule.target:
        case QueueTarget(topic=topic):
            return f"topic {topic}"
        case FunctionTarget(function=function):
            return f"function {function}"
        case PathTarget(path=path):
            return f"path {path}"
```

## Get a schedule

`get_schedule()` returns one static or dynamic schedule by name:

```python
from vercel.schedules import get_schedule

schedule = await get_schedule("cleanup")
```

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| `name` | `str` | Yes | Schedule name |
| `namespace` | `str` | No | Defaults to `default` |

Raises a `ScheduleNotFoundError` if the schedule doesn't exist.

## Update a schedule

`update_schedule()` changes a dynamic schedule. Arguments you leave out keep their current values:

```python
from vercel.schedules import update_schedule

await update_schedule(
    "cleanup",
    cron="0 2 * * *",
    payload={"max_age_days": 60},
)
```

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| `name` | `str` | Yes | Schedule name |
| `namespace` | `str` | No | Defaults to `default` |
| `cron` | `Cron` or `str` | No | New cron expression. You can't change a one-time schedule to a cron schedule. |
| `at` | `datetime` | No | New one-time run, with the same rules as [`create_schedule()`](#create-a-one-time-schedule). You can't change a cron schedule to a one-time schedule. |
| `timezone` | `str` | No | New IANA timezone. Applies to the new expression, or on its own, to the existing one. |
| `topic` | `str` | No | New queue topic |
| `jitter` | `timedelta` or `None` | No | New jitter window. Pass `None` to return to the default. On Hobby, the window stays at 15 minutes. |
| `payload` | Any JSON value | No | New payload. Pass `None` to remove it. |

Returns the updated [`Schedule`](#schedule). Raises a `SchedulesValidationError` if you don't pass anything to change.

You can't update a static schedule. Edit your configuration and redeploy instead. To change a schedule's expression type, delete it and create it again.

## Enable and disable a schedule

`enable_schedule()` and `disable_schedule()` change whether a static or dynamic schedule runs on its cadence:

```python
from vercel.schedules import disable_schedule, enable_schedule

await disable_schedule("cleanup")
await enable_schedule("cleanup")
```

Pass `until` to `enable_schedule()` to enable the schedule until a set time:

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

await enable_schedule(
    "cleanup",
    until=datetime.now(timezone.utc) + timedelta(hours=2),
)
```

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| `name` | `str` | Yes | Schedule name |
| `namespace` | `str` | No | Defaults to `default` |
| `until` | `datetime` | No | `enable_schedule()` only. Time to disable the schedule again, as an aware `datetime`. Must be in the future. |

Both functions return the updated [`Schedule`](#schedule). When you pass `until`:

- The schedule's `active_until` attribute holds the end time until it passes.
- Calling `enable_schedule()` again with `until` replaces the end time.
- Calling `enable_schedule()` without `until` keeps the schedule active indefinitely.
- If the schedule is already active indefinitely, the call fails with code `schedule_already_active`. Disable it first.

## Invoke a schedule

`invoke_schedule()` runs a static or dynamic schedule now, without changing its state or cadence:

```python
from vercel.schedules import invoke_schedule

await invoke_schedule("cleanup")
```

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| `name` | `str` | Yes | Schedule name |
| `namespace` | `str` | No | Defaults to `default` |

The function returns once Vercel accepts the run. Your target receives it shortly afterward, the same way as a scheduled run. You can invoke an inactive schedule.

## Delete a schedule

`delete_schedule()` deletes a dynamic schedule and stops its future runs:

```python
from vercel.schedules import delete_schedule

await delete_schedule("cleanup")
```

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| `name` | `str` | Yes | Schedule name |
| `namespace` | `str` | No | Defaults to `default` |

You can't delete a static schedule. Remove it from your configuration and redeploy instead.

After you delete a schedule, you can create a new one with the same name right away. You can delete a one-time schedule before it runs or after its run is dispatched, but not while the run is being dispatched. See [Delete a schedule](/docs/schedules/manage#delete-a-schedule).

## Handle scheduled runs

When a schedule runs a function or path, Vercel sends the run's details in [request headers](/docs/schedules/handle-runs#request-headers). `ScheduleMetadata.from_headers()` reads them and returns the run's [`ScheduleMetadata`](#schedule-metadata):

```python filename="api/cleanup.py"
import hmac
import os

from fastapi import FastAPI, HTTPException, Request
from vercel.schedules import ScheduleEventParseError, ScheduleMetadata

app = FastAPI()


@app.post("/api/cleanup")
async def cleanup(request: Request) -> None:
    cron_secret = os.environ.get("CRON_SECRET")
    auth_header = request.headers.get("authorization")
    if not cron_secret or not auth_header or not hmac.compare_digest(
        auth_header, f"Bearer {cron_secret}"
    ):
        raise HTTPException(status_code=401, detail="Unauthorized")

    try:
        metadata = ScheduleMetadata.from_headers(request.headers)
    except ScheduleEventParseError as exc:
        raise HTTPException(status_code=400, detail=str(exc)) from exc

    print(f"{metadata.name} run {metadata.execution_id}")
    await delete_expired_records()
```

It raises `NotAScheduleInvocationError` (a subclass of `ScheduleEventParseError`) if the request isn't a schedule run, such as a direct request or a [Cron Job](/docs/schedules/cron-jobs), and `ScheduleEventParseError` if a header is missing or invalid. A path is public, so [check the `CRON_SECRET`](/docs/schedules/handle-runs#path-targets) before you do any work.

See [Handling scheduled runs](/docs/schedules/handle-runs) for function, path, and queue examples.

## Errors

The SDK raises these errors. All of them are subclasses of `SchedulesError`:

| Error | Raised when |
| --- | --- |
| `SchedulesApiError` | The API returns an error response |
| `ScheduleNotFoundError` | The schedule doesn't exist in this namespace. A subclass of `SchedulesApiError` and `LookupError`. |
| `SchedulesValidationError` | The SDK rejects your arguments before it sends a request. A subclass of `ValueError`. |
| `SchedulesCredentialsError` | The SDK can't find a token |
| `SchedulesResponseError` | The API returns a successful response that the SDK can't read |
| `ScheduleEventParseError` | A schedule dispatch has missing or invalid headers |
| `NotAScheduleInvocationError` | A request isn't a schedule run. A subclass of `ScheduleEventParseError`. |

`SchedulesApiError` has these attributes:

| Attribute | Type | Description |
| --- | --- | --- |
| `status_code` | `int` | HTTP status code |
| `code` | `str` or `None` | Machine-readable error code |
| `retry_after` | `int` or `None` | Seconds to wait before retrying, when the API sends a `Retry-After` header |
| `request_id` | `str` or `None` | The `x-vercel-id` response header. Include it when you contact support. |

A `not_found` response raises `ScheduleNotFoundError`. Other common codes:

| Code | Cause |
| --- | --- |
| `forbidden` | Your role can't make this change in this environment. See [Permissions](/docs/schedules/manage#permissions). |
| `feature_blocked` | Your Hobby team went over its [usage limits](/docs/schedules/limits#hobby-limits) for this billing period |
| `schedule_already_exists` | A schedule with this name already exists in this namespace |
| `schedule_limit_exceeded` | Your team reached its [schedule limit](/docs/schedules/limits#schedules-per-team) |
| `invalid_cron_expression` | The cron expression isn't valid. See [Cron expressions](/docs/schedules/configuration#cron-expressions). |
| `invalid_jitter` | The jitter window isn't allowed on your plan |
| `jitter_exceeds_cadence` | The jitter window is longer than the shortest interval between runs |
| `single_at_in_past` | The one-time schedule's `at` time is in the past |
| `payload_too_large` | The payload is larger than 16 KB |
| `schedule_type_change_not_allowed` | You tried to change a cron schedule to a one-time schedule, or the reverse |
| `schedule_already_active` | You passed `until` to a schedule that's already active indefinitely |
| `active_until_in_past` | The `until` time isn't in the future |
| `static_schedule` | You tried to update or delete a static schedule |
| `schedule_single_at_passed` | You tried to enable, disable, or update a one-time schedule after its scheduled time, or to delete it while its run is being dispatched |
| `rate_limited` | You exceeded an [API request limit](/docs/schedules/limits#api-requests). Wait `retry_after` seconds. |
| `service_unavailable` | The Schedules API is temporarily unavailable. Retry later. |

```python
from vercel.schedules import Schedule, ScheduleNotFoundError, get_schedule


async def find_schedule(name: str) -> Schedule | None:
    try:
        return await get_schedule(name)
    except ScheduleNotFoundError:
        return None
```

## Types

### `Schedule`

`create_schedule()`, `get_schedule()`, `query_schedules()`, `update_schedule()`, `enable_schedule()`, and `disable_schedule()` return `Schedule` objects:

| Attribute | Type | Description |
| --- | --- | --- |
| `schedule_id` | `str` | Schedule ID |
| `owner_id` | `str` | ID of the team that owns the schedule |
| `project_id` | `str` | ID of the project |
| `name` | `str` | Schedule name |
| `namespace` | `str` | Schedule namespace |
| `expression` | `Cron` or `OneOffExpression` | A [`Cron`](#cron), or a `OneOffExpression` whose `at` is a naive `datetime` in the schedule's `timezone` |
| `timezone` | `str` | IANA timezone |
| `jitter` | `timedelta` or `None` | Jitter window, when set. `None` when the schedule uses the plan default. |
| `target` | `QueueTarget`, `FunctionTarget`, or `PathTarget` | See the next table |
| `state` | `ScheduleState` | `ScheduleState.ACTIVE` or `ScheduleState.INACTIVE`. A one-time schedule stays active after it runs. `schedule.is_active` returns `True` when it's active. |
| `active_until` | `datetime` or `None` | When a temporarily enabled schedule becomes inactive, in UTC. Only set while that window is open. |
| `source` | `ScheduleSource` | `ScheduleSource.STATIC` for schedules from your configuration, or `ScheduleSource.DYNAMIC` for schedules from the API |
| `created_at` | `datetime` | When the schedule was created, in UTC |
| `updated_at` | `datetime` | When the schedule last changed, in UTC |

`target` has one of these types:

| Type | Attributes | Available for |
| --- | --- | --- |
| `QueueTarget` | `topic: str` | Static and dynamic schedules |
| `FunctionTarget` | `function: str`, `service: str \| None` | Static schedules |
| `PathTarget` | `path: str`, `request_method: 'GET' \| 'POST' \| None` | Static schedules |

### Schedule metadata

`ScheduleMetadata.from_headers()` returns `ScheduleMetadata`:

| Attribute | Type | Description |
| --- | --- | --- |
| `schedule_id` | `str` | Schedule ID |
| `execution_id` | `str` | ID of this run. Stays the same if the run is delivered more than once. |
| `name` | `str` | Schedule name |
| `namespace` | `str` | Schedule namespace |
| `scheduled_at` | `datetime` | Time the expression matched, in UTC. Doesn't include jitter. |
| `source` | `str` | `static` or `dynamic` |
| `expression` | `str` | The cron expression, or the local datetime of a one-time schedule |

## Related

- [JS SDK Reference](/docs/schedules/sdk/javascript)
- [Handling scheduled runs](/docs/schedules/handle-runs)
- [Multi-tenant schedules](/docs/schedules/multi-tenant)
- [`vercel schedules` reference](/docs/cli/schedules)

## Search the docs from your terminal

Search the Vercel docs and read pages as Markdown with the Vercel CLI. No login required.

```bash
# Find docs pages by keyword
npx vercel@latest docs search "environment variables"
npx vercel@latest docs search "function timeout"

# Print a docs page as Markdown, by path or URL
npx vercel@latest docs inspect <page>
```

## Search guides from your terminal

Search the Knowledge Base and read guides as Markdown with the Vercel CLI. No login required.

```bash
# Find guides by keyword
npx vercel@latest kb search "rewrites and redirects"
npx vercel@latest kb search "AI SDK streaming"

# Show the latest guides
npx vercel@latest kb

# Print a guide as Markdown, by slug or URL
npx vercel@latest kb inspect <guide>
```

---

[View full sitemap](/docs/sitemap)


If you encounter incorrect information, can’t find what you need, need a capability Vercel doesn’t currently offer, or have any other feedback to report, please do it by following the instructions at https://vercel.com/feedback.md.
