Sub topic 12
Turning notebooks into scheduled jobs
This chapter assumes you can run a notebook against a cluster, query a table by its three-level Unity Catalog name, and tell all-purpose compute from SQL warehouses. It covers how a notebook that works interactively becomes an unattended, scheduled job.
Why notebooks need to become jobs
A notebook run by hand depends on a person. Someone opens it, attaches compute, and clicks Run. That is fine for exploration. It fails for a nightly load, a daily report, or a pipeline that must finish before the business day starts.
A job is a Databricks object that runs work without a person present. Jobs are part of Databricks Workflows, the orchestration feature of the platform. A job has one or more tasks, each task runs a unit of work, and a trigger decides when the job starts. Every execution of a job is a run.
The parts of a job
| Part | What it is | Example |
|---|---|---|
| Job | The named, saved definition | `nightly_orders_refresh` |
| Task | One unit of work inside the job | A notebook, a Python script, a SQL query, a pipeline |
| Dependency | An edge saying one task waits for another | `aggregate` runs after `ingest` succeeds |
| Trigger | What starts a run | A cron schedule, a file arrival, a manual click, an API call |
| Compute | Where each task runs | Job compute, serverless compute, or a SQL warehouse |
| Parameters | Values passed into tasks at run time | `run_date = 2026-12-04` |
| Run | One execution of the job | Run 4521, started 02:00 |
A job with several tasks forms a directed acyclic graph (DAG). Tasks with no dependency between them run in parallel. A task whose upstream task failed is skipped by default.
Choosing compute for a job
The compute choice is the most important cost decision for a scheduled job. The options differ in how they start and what they cost.
- Job compute is a cluster created when the run starts and terminated when it ends. It is billed at a lower rate than all-purpose compute. Startup typically takes a few minutes.
- Serverless compute for jobs is managed by Databricks and starts quickly. You do not configure cluster size.
- A SQL warehouse runs SQL tasks. Notebook tasks that use Python cannot run on a warehouse.
- All-purpose compute is the shared interactive cluster. It works for jobs, but it costs more and other users' work can compete with yours. Use it for development, not production schedules.
Tasks in one job can share a job cluster so that several notebook tasks pay the startup cost once.
Prepare a notebook for unattended runs
A notebook written for exploration usually needs three changes before it is safe to schedule.
- Accept parameters. Hard-coded dates and table names make a notebook run the same way forever. Use widgets, which are small input controls that a job can fill in.
- Fail loudly. A job treats a run as successful if the notebook finishes without raising an error. Code that catches exceptions and prints a message produces a green run with bad data.
- Be safe to run twice. Retries and manual reruns happen. A notebook that appends rows every time creates duplicates. Prefer writes that can be repeated safely, such as replacing one date's partition or using
MERGE.
The following notebook cell reads a date parameter, validates it, and writes a daily summary table. It reuses the main.tutorial.orders table from earlier chapters.
from datetime import date
from pyspark.sql import functions as F
dbutils.widgets.text("run_date", str(date.today()))
run_date = dbutils.widgets.get("run_date")
# Raises ValueError for a malformed date, which fails the task.
date.fromisoformat(run_date)
spark.sql("""
CREATE TABLE IF NOT EXISTS main.tutorial.daily_totals (
order_date DATE,
customer_id BIGINT,
total_amount DECIMAL(18, 2)
)
""")
daily = (
spark.table("main.tutorial.orders")
.where(F.to_date("order_ts") == F.lit(run_date).cast("date"))
.groupBy(F.to_date("order_ts").alias("order_date"), "customer_id")
.agg(F.sum("amount").cast("decimal(18,2)").alias("total_amount"))
)
# Replace only this date's rows, so a rerun does not duplicate data.
(
daily.write
.mode("overwrite")
.option("replaceWhere", f"order_date = '{run_date}'")
.saveAsTable("main.tutorial.daily_totals")
)replaceWhere overwrites only the rows that match the condition. Running the notebook twice for the same run_date leaves the table in the same state. The date.fromisoformat call also stops a malformed value from reaching the SQL condition string.
Create the job
You can create a job in the Workflows page of the workspace, or define it as code. The steps in the interface are:
- Open Jobs & Pipelines (named Workflows in some workspaces) and choose Create job.
- Add a task. Set its type to Notebook, pick the notebook path, and choose the compute.
- Add a parameter named
run_date. - Add a trigger. Choose a schedule and a time zone.
- Add notifications for failure, and set a retry count if the task can fail temporarily.
- Run it once manually and check the result before relying on the schedule.
The same job as a definition for the Jobs API or Databricks CLI is below. Field names follow the Jobs API 2.1 format. The notebook path and email address are placeholders you must replace.
{
"name": "nightly_orders_refresh",
"tasks": [
{
"task_key": "daily_totals",
"notebook_task": {
"notebook_path": "/Workspace/Users/[email protected]/daily_totals",
"base_parameters": { "run_date": "{{job.start_time.iso_date}}" }
},
"max_retries": 2,
"min_retry_interval_millis": 60000,
"timeout_seconds": 3600
}
],
"schedule": {
"quartz_cron_expression": "0 0 2 * * ?",
"timezone_id": "UTC",
"pause_status": "UNPAUSED"
},
"email_notifications": { "on_failure": ["[email protected]"] }
}A task with no compute settings in this definition uses serverless compute where your workspace supports it. In other workspaces, add a job_cluster_key that points to a cluster definition.
Triggers and run behavior
Databricks offers several triggers.
- Scheduled uses a Quartz cron expression. The expression
0 0 2 * * ?means second 0, minute 0, hour 2, every day. Pick a time zone explicitly. A schedule in a daylight-saving zone can skip or repeat an hour on the changeover day. - File arrival starts a run when new files land in a Unity Catalog volume or external location.
- Continuous restarts the job as soon as a run ends, which suits streaming work.
- Manual or API is useful for tests and for external schedulers such as Airflow.
By default a job allows one active run at a time. If a run is still going when the next trigger fires, the new run is skipped. Raise the concurrency limit only if your notebook is safe to run in parallel with itself.
Permissions and identity
A job runs as an identity. By default this is the job's creator. If that person leaves or loses access, the job starts failing with permission errors. For production, set the job to run as a service principal, which is an identity for automation that is not tied to a person.
The run-as identity needs privileges in Unity Catalog, as the earlier governance chapter described.
GRANT USE CATALOG ON CATALOG main TO `etl-service-principal`;
GRANT USE SCHEMA, SELECT, MODIFY, CREATE TABLE ON SCHEMA main.tutorial TO `etl-service-principal`;A service principal is referenced by its application ID in grants in some workspaces. Check how yours displays it.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Run succeeds but the table is empty | The notebook caught an error, or `run_date` had no data | Remove broad `try/except`, and check the row count |
| Duplicate rows after a retry | The write appends | Use `replaceWhere` or `MERGE` |
| `PERMISSION_DENIED` on a table | The run-as identity lacks `USE CATALOG`, `USE SCHEMA`, or `SELECT` | Grant the privileges to that identity |
| Run skipped | A previous run is still active | Shorten the run, or review concurrency |
| Schedule fires at the wrong hour | Time zone not set as intended | Set `timezone_id` |
| Bill is higher than expected | Job runs on all-purpose compute | Switch to job or serverless compute |
Monitoring runs
The Runs tab lists each run with its status, duration, and trigger. Opening a run shows the notebook output as it executed, so you can see the failing cell. Failure notifications can go to email, Slack, or a webhook. A repair run reruns only the failed tasks and the tasks that depend on them, which saves compute when the first task of a long job succeeded.
Exercise
Your nightly job appends yesterday's orders to a summary table. A transient network error fails the task, and the retry then succeeds. The next morning the totals for that day are doubled. What caused this, and what two changes fix it?
Show answer
The first attempt wrote some or all of its rows before failing, and the retry appended again, so the data was written twice. Make the write repeatable: use replaceWhere for the run date or a MERGE on a key. Also pass the date as a job parameter so a rerun targets the same day explicitly.
Exercise
A job runs as its creator. That person moves to another team and loses access to the main.tutorial schema. What happens at the next scheduled run, and what is the lasting fix?
Show answer
The run fails with a permission error because the run-as identity can no longer read or write the tables. The lasting fix is to set the job to run as a service principal and grant that service principal the needed Unity Catalog privileges.