How to Schedule a Task in Snowflake: Step-by-Step Guide
In Snowflake, you schedule a task using the
CREATE TASK command with a WAREHOUSE and a SCHEDULE clause that supports cron syntax. This lets you automate SQL statements to run at specific times or intervals.Syntax
The basic syntax to schedule a task in Snowflake includes defining the task name, the warehouse to run it, the schedule using cron syntax, and the SQL statement to execute.
- CREATE TASK task_name: Names the task.
- WAREHOUSE = warehouse_name: Specifies the compute resource.
- SCHEDULE = 'USING CRON cron_expression': Sets when the task runs.
- AS sql_statement: Defines the SQL to execute.
sql
CREATE TASK task_name WAREHOUSE = warehouse_name SCHEDULE = 'USING CRON cron_expression' AS sql_statement;
Example
This example creates a task that runs every day at 1 AM to insert a record into a log table.
sql
CREATE OR REPLACE TASK daily_log_task WAREHOUSE = my_warehouse SCHEDULE = 'USING CRON 0 1 * * * UTC' AS INSERT INTO task_log (log_time, message) VALUES (CURRENT_TIMESTAMP, 'Daily task ran'); -- To start the task after creation ALTER TASK daily_log_task RESUME;
Output
Task daily_log_task created and scheduled to run daily at 1 AM UTC.
Common Pitfalls
Common mistakes when scheduling tasks in Snowflake include:
- Not specifying a warehouse, which causes the task to fail.
- Using incorrect cron syntax or time zone, leading to unexpected run times.
- Forgetting to
RESUMEthe task after creation, so it stays suspended. - Running tasks without proper privileges or on non-existent tables.
sql
/* Wrong: Missing warehouse and task stays suspended */ CREATE TASK wrong_task SCHEDULE = 'USING CRON 0 0 * * * UTC' AS SELECT 1; /* Right: Specify warehouse and resume task */ CREATE TASK correct_task WAREHOUSE = my_warehouse SCHEDULE = 'USING CRON 0 0 * * * UTC' AS SELECT 1; ALTER TASK correct_task RESUME;
Quick Reference
| Clause | Description | Example |
|---|---|---|
| CREATE TASK | Defines the task name | CREATE TASK my_task |
| WAREHOUSE | Specifies the compute warehouse | WAREHOUSE = my_warehouse |
| SCHEDULE | Sets the cron schedule | SCHEDULE = 'USING CRON 0 1 * * * UTC' |
| AS | SQL statement to run | AS INSERT INTO table VALUES (1) |
| ALTER TASK ... RESUME | Starts the task after creation | ALTER TASK my_task RESUME |
Key Takeaways
Always specify a warehouse when creating a task to ensure it runs.
Use the SCHEDULE clause with cron syntax to set task timing precisely.
Remember to resume the task after creation; tasks start suspended by default.
Check permissions and object existence to avoid task failures.
Use ALTER TASK to manage task state and schedule changes.
