Google Cloud Scheduler Client Library

2.19.0 · active · verified Sat Apr 11

The `google-cloud-scheduler` Python client library allows developers to programmatically create, manage, and delete Cloud Scheduler jobs. Cloud Scheduler is a fully managed cron job service that enables you to schedule virtually any asynchronous task, such as invoking HTTP endpoints, publishing messages to Pub/Sub topics, or triggering App Engine applications. The library is actively maintained by Google, with frequent releases, and is currently at version 2.19.0.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create a simple Cloud Scheduler job that triggers an HTTP endpoint every hour using the `scheduler_v1` API. Ensure your `GCP_PROJECT_ID`, `GCP_LOCATION_ID`, `SCHEDULER_JOB_NAME`, and `SCHEDULER_TARGET_URL` environment variables are set or replaced in the code. Authentication is handled automatically via Application Default Credentials if running in a Google Cloud environment or with `gcloud auth application-default login` locally.

import os
from google.cloud import scheduler_v1

project_id = os.environ.get('GCP_PROJECT_ID', 'your-project-id')
location_id = os.environ.get('GCP_LOCATION_ID', 'us-central1') # e.g., 'us-central1'
job_name = os.environ.get('SCHEDULER_JOB_NAME', 'my-scheduled-job')
target_url = os.environ.get('SCHEDULER_TARGET_URL', 'https://your-http-endpoint.cloudfunctions.net/myFunction')

# Initialize a client
client = scheduler_v1.CloudSchedulerClient()

# Construct the full resource name of the parent of the job
parent = client.location_path(project_id, location_id)

# Construct the job body
job = scheduler_v1.Job()
job.name = client.job_path(project_id, location_id, job_name)
job.description = 'My first Cloud Scheduler job (Python client)'
job.schedule = '0 * * * *'  # Run every hour
job.time_zone = 'America/Los_Angeles'

# Configure an HTTP target
http_target = scheduler_v1.HttpTarget()
http_target.uri = target_url
http_target.http_method = scheduler_v1.HttpMethod.POST
job.http_target = http_target

# Create the job
try:
    response = client.create_job(parent=parent, job=job)
    print(f'Created job: {response.name}')
except Exception as e:
    print(f'Error creating job: {e}')

# To delete the job (uncomment to run)
# try:
#     client.delete_job(name=response.name)
#     print(f'Deleted job: {response.name}')
# except Exception as e:
#     print(f'Error deleting job: {e}')

view raw JSON →