---
title: Scheduled detection rules
description: "Write and create scheduled Lakewatch detection rules: configure a SQL warehouse and schedule, scope time windows, and handle late-arriving data."
canonical_url: https://docs.databricks.com/aws/en/lakewatch/detections/scheduled-detection-rules
---

# Scheduled detection rules

> [!NOTE]
> **Beta**
>
> Lakewatch is in [Beta](https://docs.databricks.com/aws/en/release-notes/release-types.md). Workspace admins can control access to this feature from the **Previews** page. See [ Manage workspace-level previews](https://docs.databricks.com/aws/en/admin/workspace-settings/manage-previews.md#workspace).

A scheduled detection rule runs a SQL query over a time window on a schedule. This page explains how to write the query, create the rule, and handle time windows and late-arriving data. To compare scheduled and streaming rules, see [Choose a detection rule type](https://docs.databricks.com/aws/en/lakewatch/detections/choose-detection-rule-type.md).

## <a id="how-detection-rules-run" />How scheduled rules run

A scheduled rule runs your detection SQL over a time window at a specified interval. Each run generates a [signal](https://docs.databricks.com/aws/en/lakewatch/detections/signals.md) for each match. You write the full query, including the `FROM` clause, so a rule can join tables, scan a whole table, or compute aggregates. Each rule runs its SQL on a SQL warehouse you provide. See [Set up a warehouse for scheduled detections](https://docs.databricks.com/aws/en/lakewatch/admin/detection-warehouse.md).

## Before you begin

Design your detection logic and select a SQL warehouse that meets the [detection warehouse prerequisites](https://docs.databricks.com/aws/en/lakewatch/admin/detection-warehouse.md#prerequisites). The rule runs as its run-as principal, which must have access to the tables it reads. See [Set the run-as principal](https://docs.databricks.com/aws/en/lakewatch/detections/manage-detection-rules.md#run-as-principal).

## <a id="create-a-scheduled-rule" />Create a scheduled rule

To create a scheduled rule, complete the following steps:

1. Go to **Detection rules** and click **Create detection rule**.
2. Under **Choose a rule type**, on **Scheduled rule**, click **Use scheduled rule**.
3. In **Detection input**, configure the following fields:
   * **Folder**, **Rule name**, and **Description**: See [Configure common rule settings](https://docs.databricks.com/aws/en/lakewatch/detections/manage-detection-rules.md#rule-configuration).
   * **SQL warehouse** (required): Select the warehouse that runs the detection SQL. Each rule runs in its own isolated job. Rules don't use cluster grouping or custom compute settings.
   * **Detection SQL** (required): Enter the full query, including the `FROM` clause. Use `IN_TIMERANGE()` to [scope the query to its time range](https://docs.databricks.com/aws/en/lakewatch/detections/scheduled-detection-rules.md#scope-rules-to-a-time-range).
   * **Extend lookback**: Set a duration to include late-arriving data, or leave it blank to use the default. See [Extend the window with `extend_lookback`](https://docs.databricks.com/aws/en/lakewatch/detections/scheduled-detection-rules.md#extend-the-window-with-extend_lookback).
4. Configure [signal output](https://docs.databricks.com/aws/en/lakewatch/detections/manage-detection-rules.md#signals), [MITRE ATT\&CK mappings](https://docs.databricks.com/aws/en/lakewatch/detections/manage-detection-rules.md#mitre-attck), and [metadata](https://docs.databricks.com/aws/en/lakewatch/detections/manage-detection-rules.md#metadata).
5. In **Execution**, [set the schedule](https://docs.databricks.com/aws/en/lakewatch/detections/scheduled-detection-rules.md#set-a-schedule) and use **Active** to turn the rule on or off. To change its identity, click **Edit run as principal**.
6. Click **Create rule**, and then confirm.

Lakewatch creates the rule. Active rules run on their schedule and generate a [signal](https://docs.databricks.com/aws/en/lakewatch/detections/signals.md) for each match.

The confirmation step states that the environment, folder, and rule name can't change after creation. To use a different environment, folder, or name, create a new rule. Click **Cancel** to discard an unsaved rule, then confirm the cancellation.

## <a id="set-a-schedule" />Set a schedule

In **Execution**, select one of the following schedule types:

* **At least every**: The rule runs at least this often (minimum 5 minutes), but might run more frequently under certain circumstances. Set an amount and a unit: minutes, hours, or days.
* **Exactly at**: The rule runs on a cron schedule. Build it with the **Every *N*** selector and a unit (minute, hour, day, week, or month), then set the time of day with the controls that follow, or select **Show cron syntax** to enter a Quartz cron expression directly. Times are in UTC.

Lakewatch accepts a subset of Quartz cron syntax. Use six fields, or seven with `*` for the year. The seconds field must be a single integer from 0 through 59. Exactly one of the day-of-month and day-of-week fields must be `?`. Extensions such as `L`, `W`, `#`, and `C` aren't supported. Cron schedules must have at least 5 minutes between runs.

## <a id="scope-rules-to-a-time-range" />Scope rules to a time range

Whenever possible, scope a rule to a relevant time range rather than scanning an entire table. Use the `IN_TIMERANGE` function to express that window, and let the run supply the bounds:

```sql
SELECT *
FROM process_activity
WHERE IN_TIMERANGE(<event_time>)
  AND activity_id = 1
  AND endswith(lower(process.name), '\\hashcat.exe')
```

Replace `<event_time>` with the `TIMESTAMP` column or expression to filter.

`IN_TIMERANGE(<event_time>)` returns true when an event falls within the effective time range of the current run. The range is half-open: an event whose timestamp equals the window's start is included, but one that equals the end is excluded. This avoids sharing an endpoint between nonoverlapping windows. A nonzero `extend_lookback` intentionally makes consecutive windows overlap. Signal deduplication controls repeated signals from matching rows. You don't write the start and end times into the SQL yourself. Instead, Lakewatch supplies the range based on how the query runs:

* For a scheduled run, the base window starts at the previous scheduled fire time and ends at the current scheduled fire time. This time window is unaffected by scheduling delays. To account for ingestion lag, see [Extend the window with `extend_lookback`](https://docs.databricks.com/aws/en/lakewatch/detections/scheduled-detection-rules.md#extend-the-window-with-extend_lookback).
* On the query page (which you can use to develop a rule), you select the window using the date/time picker. Because SQL written on the query page does not itself contain the time range, it can be deployed as a detection rule unchanged.

### <a id="extend-the-window-with-extend_lookback" />Extend the window with `extend_lookback`

`IN_TIMERANGE(<event_time>)` filters on event time, but logs often reach the table minutes after the event occurs. A row can land *after* the run whose window covered its event time has already finished, and later runs scan newer event times, creating a coverage gap. `extend_lookback`, an optional per-rule setting, moves the window's start earlier so each run rescans a slice of older event time and catches rows that arrived since the last run. It shifts only the earliest bound. The latest bound stays at the current scheduled fire time. Set it to a duration such as `30s`, `10m`, or `2h`. The window a scheduled rule scans is its schedule cadence plus `extend_lookback`:

| `extend_lookback`   | Schedule         | Time range scanned (ending at the scheduled fire time) |
| ------------------- | ---------------- | ------------------------------------------------------ |
| Unset (default 15m) | Every 5 minutes  | The previous 20 minutes                                |
| `0s`                | Every 5 minutes  | The previous 5 minutes                                 |
| `12m`               | Every 30 minutes | The previous 42 minutes                                |
| `5h`                | Every 10 minutes | The previous 5 hours and 10 minutes                    |

Overlapping runs can select the same row multiple times. Keep signal deduplication enabled. The automatic deduplication window accounts for `extend_lookback` when the SQL uses `IN_TIMERANGE`, so a longer lookback lengthens it. If you set a custom deduplication window, make it at least as long as the time range scanned. Avoid adding changing values such as `CURRENT_TIMESTAMP()` to the SQL result solely for bookkeeping, because changed result rows are not duplicates. See [Signal deduplication](https://docs.databricks.com/aws/en/lakewatch/detections/signals.md#signal-deduplication).

If you don't set `extend_lookback`, Lakewatch applies a default of 15 minutes. Most enterprise sources deliver within a few minutes, but few guarantee an upper bound, so the default absorbs typical late arrivals without any tuning.

To set `extend_lookback` in the UI, enter a duration in **Extend lookback**, next to the detection SQL. Use ordered day, hour, minute, and second values, such as `15m` or `1h30m`. Leave it blank to use the 15-minute default, or enter `0s` to turn off the extension. The setting has no effect unless your SQL uses `IN_TIMERANGE`.

### Select the right time column

An event-time column paired with `extend_lookback` is the right approach for nearly every rule. Estimate your source's ingestion lag and set `extend_lookback` to cover it, or rely on the 15-minute default for sources that deliver promptly.

Use the event timestamp from the table you're querying. Parsed tables produced by cloud storage and existing-table datasources have a `time` column, but API connector output tables can use a different name. For example, use `IN_TIMERANGE(effective_at)` for OpenAI audit events or `IN_TIMERANGE(createdDateTime)` for Microsoft Graph security alerts. See [Query requirements](https://docs.databricks.com/aws/en/lakewatch/queries/index.md#query-requirements) for source timestamp examples.

If a source's ingestion latency is so variable that no single `extend_lookback` reliably covers it, you can instead scope the rule on ingestion time. On tables produced by a Lakewatch datasource, the `lw_meta.ingestion_time` column records when Lakewatch wrote each row after ingestion, so a window over it is unaffected by delivery delays:

```sql
WHERE IN_TIMERANGE(lw_meta.ingestion_time)
```

Reach for this only when event time plus `extend_lookback` can't do the job. Each run then covers a fixed slice of *ingestion* time rather than *event* time, so an event's own timestamp can fall outside the run's nominal window, which can skew time-bucketed aggregations. Try to solve it with event time first.

### Avoid anchoring to `NOW()` or `CURRENT_TIMESTAMP()`

A common pattern hand-writes the window against the current wall-clock time:

```sql
-- Avoid this
WHERE time BETWEEN CURRENT_TIMESTAMP() - INTERVAL 24 HOUR AND CURRENT_TIMESTAMP()
```

This works for a routine run, but can create problems:

* **Missed or double-counted data**: A window like "the last hour" is anchored to when the run fires, not the slice it was meant to cover. If a 3:00 run is delayed to 3:12, it scans 2:12 to 3:12, leaves a 2:00 to 2:12 gap, and might overlap the next run. `IN_TIMERANGE` derives the window from the scheduled slice, so a delayed run doesn't leave a gap. Overlap between scheduled runs comes from `extend_lookback`. See [Extend the window with `extend_lookback`](https://docs.databricks.com/aws/en/lakewatch/detections/scheduled-detection-rules.md#extend-the-window-with-extend_lookback).
* **Schedule changes**: If you change a rule from every 15 minutes to every 30 minutes, a hardcoded `INTERVAL 15 MINUTES` is wrong until you remember to edit it. With `IN_TIMERANGE`, the window follows the schedule.
* **Re-windowing**: Backfilling a missed period, replaying after a data fix, or previewing a new rule against older data all run the same rule over a different window. A query locked to `NOW()` can't do that without manual edits.
* **Reproducibility**: With the same bounds, `IN_TIMERANGE` scans the same rows on every run, so results are repeatable. A query tied to `NOW()` shifts with each execution.

Reserve `NOW()` and `CURRENT_TIMESTAMP()` for cases when you want to reference the real wall-clock time, such as computing how old an event is relative to the present moment.

### <a id="reference-the-runs-window-with-timerange_now" />Reference the run's window with `TIMERANGE_NOW()`

When you want a "now" value that respects the run's window rather than the wall clock, use `TIMERANGE_NOW()`. It returns the run's scheduled fire time. On the query page, it returns the end of the selected time range, to test a rule's predicates against historical data. When no time range is set, it returns the actual current time. Use it to hand-build a window that `IN_TIMERANGE` can't express, such as offsetting the window or scanning two nonadjacent periods in a single run:

| Schedule         | Predicate                                                                                                                                                         | Result                                                                                                       |
| ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ |
| Every 10 minutes | `time >= TIMERANGE_NOW() - INTERVAL 17 MINUTE AND time < TIMERANGE_NOW() - INTERVAL 7 MINUTE`                                                                     | Shifts the 10-minute window 7 minutes into the past                                                          |
| Every day        | `(time >= TIMERANGE_NOW() - INTERVAL 1 DAY AND time < TIMERANGE_NOW()) OR (time >= TIMERANGE_NOW() - INTERVAL 8 DAY AND time < TIMERANGE_NOW() - INTERVAL 7 DAY)` | Matches the 24 hours before the scheduled window end and the corresponding 24-hour period seven days earlier |

These predicates use fixed offsets from `TIMERANGE_NOW()`. Changing the schedule does not change their interval literals. `extend_lookback` does not widen these manually specified windows, because it changes only the managed start bound used by `IN_TIMERANGE`.

This table summarizes when to use each function:

| Goal                                           | Use                          |
| ---------------------------------------------- | ---------------------------- |
| Scope a rule to its time window                | `IN_TIMERANGE(<event_time>)` |
| Reference "now" that respects the run's window | `TIMERANGE_NOW()`            |

## <a id="deduplication" />Configure deduplication

Control whether Lakewatch skips duplicate signals produced by this rule. See [Signal deduplication](https://docs.databricks.com/aws/en/lakewatch/detections/signals.md#signal-deduplication) for how duplicates are identified and how the time window works.

* **Deduplication**: Turn on to drop signals whose entire output rows are identical within the time window. Turn off to record every signal.
* **Time window mode**: Select **Automatic** to derive the window from the rule's schedule and, when the SQL uses `IN_TIMERANGE`, its **Extend lookback**. Or select **Custom**, then enter a number and select **Minutes**, **Hours**, or **Days**. A custom window can't exceed 7 days. Databricks recommends **Automatic**. If the lookback is written into the SQL, use **Custom** and set a window at least as long as that lookback. See [Deduplication time window](https://docs.databricks.com/aws/en/lakewatch/detections/signals.md#deduplication-time-window).

## <a id="yaml" />Edit a scheduled rule as YAML

Use **Edit as YAML** to review or change the rule. The following example reads parsed authentication events and generates a signal for each matching logon. Replace `<warehouse-id>` with your SQL warehouse ID:

```yaml
catalog_name: security
schema_name: detections
rule_name: suspicious_login_activity

description: Detects login attempts from unusual locations.
severity: High
category: Behavioral
fidelity: FIDELITY_INVESTIGATIVE

schedule:
  enabled: true
  at_least_every: 1h

batch:
  warehouse_id: <warehouse-id>
  sql:
    query: |
      SELECT
        time,
        actor.user.name AS user_name,
        src_endpoint.ip AS source_ip
      FROM security.parsed.authentication_events
      WHERE IN_TIMERANGE(time)
        AND activity_name = 'Logon'

output:
  event_time_column: time
  summary: 'Suspicious login from {source_ip} by {user_name}'
  context:
    user_name: '{user_name}'
    source_ip: '{source_ip}'
  default_context: false
```

Scheduled rules use the following fields in addition to the [common rule fields](https://docs.databricks.com/aws/en/lakewatch/detections/manage-detection-rules.md#edit-a-rule-as-yaml):

| YAML field                  | Wizard field     | Required | Notes                                                                                                                                                                                                                            |
| --------------------------- | ---------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `batch.sql.query`           | Detection SQL    | Yes      | The detection query. Use `IN_TIMERANGE()` to scope it to each run's window. See [Scope rules to a time range](https://docs.databricks.com/aws/en/lakewatch/detections/scheduled-detection-rules.md#scope-rules-to-a-time-range). |
| `batch.warehouse_id`        | SQL warehouse    | Yes      | The ID of the SQL warehouse the rule runs on.                                                                                                                                                                                    |
| `deduplication`             | Deduplication    | No       | One of `DEDUPLICATION_DEFAULT`, `DEDUPLICATION_ENABLED`, or `DEDUPLICATION_DISABLED`.                                                                                                                                            |
| `deduplication_time_window` | Time window mode | No       | A duration such as `1 hour`, `24 hours`, or `7 days`, or `automatic`.                                                                                                                                                            |
| `schedule.at_least_every`   | At least every   | One of   | An interval such as `5m`, `15m`, or `1h` (minimum 5 minutes), for an **At least every** schedule.                                                                                                                                |
| `schedule.cron_expression`  | Exactly at       | One of   | A cron expression for an **Exactly at** schedule. See [Set a schedule](https://docs.databricks.com/aws/en/lakewatch/detections/scheduled-detection-rules.md#set-a-schedule) for syntax restrictions and the minimum interval.    |

## Additional resources

See the following pages:

* [Manage detection rules](https://docs.databricks.com/aws/en/lakewatch/detections/manage-detection-rules.md)
* [Set up a warehouse for scheduled detections](https://docs.databricks.com/aws/en/lakewatch/admin/detection-warehouse.md)
* [Signals](https://docs.databricks.com/aws/en/lakewatch/detections/signals.md)
