How to Schedule Tasks in GCP Using Cloud Scheduler
To schedule a task in GCP, use
Cloud Scheduler, which lets you run jobs at specified times using cron syntax. You create a scheduler job that triggers HTTP endpoints, Pub/Sub topics, or App Engine tasks on a set schedule.Syntax
The basic syntax to create a Cloud Scheduler job includes specifying the job name, schedule in cron format, target type (HTTP, Pub/Sub, or App Engine), and the target details.
- name: Unique identifier for the job.
- schedule: Cron expression defining when the job runs.
- timeZone: Time zone for the schedule.
- httpTarget: HTTP endpoint details if using HTTP trigger.
- pubsubTarget: Pub/Sub topic details if using Pub/Sub trigger.
- appEngineHttpTarget: App Engine task details if using App Engine trigger.
bash
gcloud scheduler jobs create http JOB_NAME --schedule="CRON_EXPRESSION" --uri="TARGET_URL" --http-method=METHOD --time-zone="TIME_ZONE"
Example
This example creates a Cloud Scheduler job that sends an HTTP POST request every day at 9 AM UTC to a specified URL.
bash
gcloud scheduler jobs create http daily-task --schedule="0 9 * * *" --uri="https://example.com/task" --http-method=POST --time-zone="UTC"
Output
Created job [projects/PROJECT_ID/locations/LOCATION/jobs/daily-task].
Common Pitfalls
- Using incorrect cron syntax causes the job not to run; always validate your cron expression.
- Not setting the correct time zone can lead to unexpected run times.
- For HTTP targets, ensure the endpoint is reachable and accepts the specified HTTP method.
- Missing permissions can block job creation or execution; verify IAM roles.
bash
gcloud scheduler jobs create http my-job --schedule="invalid-cron" --uri="https://example.com" --http-method=GET # Wrong: invalid cron expression gcloud scheduler jobs create http my-job --schedule="0 12 * * *" --uri="https://example.com" --http-method=GET # Right: valid cron expression
Quick Reference
Use this quick reference for common Cloud Scheduler commands and cron syntax:
| Command | Description |
|---|---|
| gcloud scheduler jobs create http JOB_NAME --schedule="CRON" --uri="URL" --http-method=METHOD | Create HTTP triggered job |
| gcloud scheduler jobs create pubsub JOB_NAME --schedule="CRON" --topic=TOPIC_NAME | Create Pub/Sub triggered job |
| gcloud scheduler jobs list | List all scheduler jobs |
| gcloud scheduler jobs delete JOB_NAME | Delete a scheduler job |
| * * * * * | Cron syntax for every minute |
Key Takeaways
Use Cloud Scheduler to run tasks on a set schedule in GCP.
Specify the schedule using standard cron syntax and set the correct time zone.
Choose the right target type: HTTP, Pub/Sub, or App Engine.
Validate cron expressions and permissions to avoid common errors.
Use gcloud CLI commands to create, list, and manage scheduler jobs.