# Chalk Python SDK Reference: Scheduled Queries
source: https://docs.chalk.ai/api-docs#section-scheduled-queries

## `ScheduledQuery`
source: https://docs.chalk.ai/api-docs#ScheduledQuery

Class

**Attributes**

- `input_checks`: `tuple[CompiledCheck, ...]`
- `output_checks`: `tuple[CompiledCheck, ...]`

### `ScheduledQuery.__init__(name, schedule, output, recompute_features, max_samples, lower_bound, upper_bound, tags, dataset_name, required_resolver_tags, store_online, store_offline, incremental_resolvers, planner_options, env_overrides, resource_group, completion_deadline, num_shards, num_workers, input_sql, unload_resolvers, max_retries, resources, environment, use_metaplanner, write_to)`
source: https://docs.chalk.ai/api-docs#ScheduledQuery.__init__

Create an offline query which runs on a schedule.

Scheduled queries do not produce datasets, but persist their results in the online and/or offline feature stores.

By default, scheduled queries use incrementalization to only ingest data that has been updated since the last run.

**Parameters**

- `name`: `str`
  A unique name for the scheduled query. The name of the scheduled query will show up in the dashboard and will be uset to set the incremetalization metadata.
- `schedule`: `CronTab | Duration`
  A cron schedule or a [`Duration`](https://docs.chalk.ai/api-docs#Duration) object representing the interval at which the query should run.
- `output`: `Collection[FeatureReference]`
  The features that this query will compute. Namespaces are exploded into all features in the namespace.
- `recompute_features`: `bool | Collection[FeatureReference]` = `True`
  Whether to recompute all features or load from the feature store. If [`True`](https://docs.python.org/3/library/constants.html#True), all features will be recomputed. If [`False`](https://docs.python.org/3/library/constants.html#False), all features will be loaded from the feature store. If a list of features, only those features will be recomputed, and the rest will be loaded from the feature store.
- `max_samples`: `int | None` = `None`
  The maximum number of samples to compute.
- `lower_bound`: `datetime | timedelta | None` = `None`
  A lower bound for the query. If set, the query will not use incrementalization. A [`datetime`](https://docs.python.org/3/library/datetime.html?highlight=datetime#datetime.datetime) is a fixed bound; a [`timedelta`](https://docs.python.org/3/library/datetime.html?highlight=datetime#datetime.timedelta) is resolved relative to each run (e.g. `-timedelta(days=7)` is the last 7 days as of the run).
- `upper_bound`: `datetime | timedelta | None` = `None`
  An upper bound for the query. If set, the query will not use incrementalization. A [`datetime`](https://docs.python.org/3/library/datetime.html?highlight=datetime#datetime.datetime) is a fixed bound; a [`timedelta`](https://docs.python.org/3/library/datetime.html?highlight=datetime#datetime.timedelta) is resolved relative to each run.
- `tags`: `Collection[str] | None` = `None`
  Allows selecting resolvers with these tags.
- `dataset_name`: `str | None` = `None`
  Associated dataset name for the scheduled query. If set, each run's output is persisted as a revision of this dataset, independently of `store_online` and `store_offline`.
- `required_resolver_tags`: `Collection[str] | None` = `None`
  Requires that resolvers have these tags.
- `store_online`: `bool` = `True`
  Whether to store the results of this query in the online store.
- `store_offline`: `bool` = `True`
  Whether to store the results of this query in the offline store.
- `incremental_resolvers`: `Collection[str] | None` = `None`
  If set to None, Chalk will incrementalize resolvers in the query's root namespaces. If set to a list of resolvers, this set will be used for incrementalization. Incremental resolvers must return a feature time in its output, and must return a [`DataFrame`](https://docs.chalk.ai/api-docs#DataFrame). Most commonly, this will be the name of a SQL file resolver. Chalk will ingest all new data from these resolvers and propagate changes to values in the root namespace.
- `planner_options`: `dict[str, str] | None` = `None`
  A dictionary of options to pass to the planner. These are typically provided by Chalk Support for specific use cases.
- `env_overrides`: `dict[str, str] | None` = `None`
  Environment variables to apply to each scheduled query run. These are typically provided by Chalk Support for specific use cases.
- `resource_group`: `str | None` = `None`
  The resource group to use for the query. If not set, the default resource group will be used.
- `completion_deadline`: `timedelta | None` = `None`
- `num_shards`: `int | None` = `None`
- `num_workers`: `int | None` = `None`
- `input_sql`: `str | None` = `None`
- `unload_resolvers`: `UnloadResolvers` = `None`
- `max_retries`: `int | None` = `None`
- `resources`: `ResourceRequests | None` = `None`
- `environment`: `str | None` = `None`
- `use_metaplanner`: `bool | None` = `None`
  Whether to route scheduled query runs through the metaplanner. If unset, the server chooses based on deployment configuration and other query settings.
- `write_to`: `str | None` = `None`
  A storage URI (e.g. `s3://bucket/path/`) to which each run's output rows are written directly, in addition to online/offline store persistence.

**Returns**

A scheduled query object.

**Examples**

```python
from chalk.queries import ScheduledQuery
# this scheduled query will automatically run every 5 minutes after `chalk apply`
ScheduledQuery(
    name="ingest_users",
    schedule="*/5 * * * *",
    output=[User],
    store_online=True,
    store_offline=True,
)
```

### `ScheduledQuery.checks_for_stage(stage)`
source: https://docs.chalk.ai/api-docs#ScheduledQuery.checks_for_stage

The checks attached at one stage.

### `ScheduledQuery.with_checks(input, output)`
source: https://docs.chalk.ai/api-docs#ScheduledQuery.with_checks

Attach data quality checks to this query, and return it so the call chains.

A check is SQL over the table being checked, built with one of the `Check` constructors. The kind you pick decides what is reported as well as what can fail:

- `Check.sql_bool(expression, name=...)` asserts that a boolean holds.
- `Check.sql_bad_rows(where, name=...)` takes a predicate matching the rows that should not exist. It fails when there are any, and reports how many there were.
- `Check.sql_metric(expression, name=..., min=..., max=...)` reports a number and optionally bounds it. The number is recorded whether or not it is thresholded, so it can be plotted and a bound chosen from the history.
- `Check.sql_distribution(expression, name=...)` reports an array as bucket counts.
- `Check.sql_raw(sql)` runs a query exactly as written, naming its own `_check` / `_metric` / `_distribution` columns. A bare string is shorthand for this.

Every kind but `sql_raw` takes a fragment is formatted with the `SELECT` around it, reading the stage's own table. Pass `from_sql=` to any of them to work over a derived table instead -- a group-by, a join, or a query that finds the bad rows itself.

Chalk sequences the checks between the step that produces the table and the step that consumes it, which is what makes them gating: a failing `input` check stops the query before it shards, and a failing `output` check stops the computed rows from being written to the online and offline stores.

**Notes**

Feature columns are dotted, so they must be quoted: `"user.email"`, not `user.email`. Because Chalk supplies the table, an `input` check cannot accidentally read `dqm.output`. `sql_raw` is the exception -- it writes its own `SELECT`, so it must name `dqm.input` or `dqm.output` itself, with the `dqm.` qualifier, and it is the only kind that can be attached to the wrong stage.

A check that evaluates to null counts as a failure, so a check that never really ran cannot pass silently. Checks are gating by default: pass `terminate_on_failure=False` to make one advisory while it is being rolled out, and failures are still logged and reported while the run proceeds. Gating is per check, so one advisory check does not make its neighbors advisory.

**Parameters**

- `input`: `Collection[str | DataQualityCheck]` = `()`
  Checks over the query's input -- its spine, however it was produced.
- `output`: `Collection[str | DataQualityCheck]` = `()`
  Checks over the query's computed output, before it is written to the stores.

**Returns**

`ScheduledQuery`

This query, so `with_checks` can wrap the declaration in place.

**Examples**

```python
from chalk.queries import Check, ScheduledQuery
ScheduledQuery(
    name="ingest_users",
    schedule="@daily",
    output=[User],
).with_checks(
    input=[
        Check.sql_metric("count(*)", min=1000, name="spine_rows"),
    ],
    output=[
        Check.sql_bad_rows('"user.email" IS NULL', name="missing_email"),
        Check.sql_metric(
            'count("user.email") * 1.0 / count(*)',
            min=0.9,
            name="email_coverage",
        ),
        Check.sql_bool(
            'max("user.age") < 120',
            name="ages_plausible",
            terminate_on_failure=False,
        ),
    ],
)
```
