Google Cloud

Cloud Scheduler + Cloud Functions/Run: Scheduled Batch Automation Tutorial

2026-05-24
NicheeLab Editorial Team

Cloud Scheduler is GCP's managed cron service, capable of triggering Cloud Functions / Cloud Run / Pub/Sub / arbitrary HTTP endpoints on a schedule. This article walks through the full set of implementation patterns: authentication, retries, parallel execution, and Workflows integration.

Pattern 1: Scheduler → Cloud Functions

# Function (Python)
import functions_framework

@functions_framework.http
def daily_report(request):
    # 処理: BigQuery 集計 → Email 送信
    from google.cloud import bigquery
    client = bigquery.Client()
    rows = client.query("SELECT COUNT(*) FROM analytics.events WHERE DATE(timestamp)=CURRENT_DATE()").result()
    # SendGrid でメール送信...
    return "OK"

# デプロイ
gcloud functions deploy daily-report \
  --gen2 --runtime=python311 --region=asia-northeast1 \
  --trigger-http --no-allow-unauthenticated \
  [email protected]

# Scheduler 設定 (OIDC 認証)
gcloud scheduler jobs create http daily-report-job \
  --schedule="0 9 * * *" \
  --time-zone="Asia/Tokyo" \
  --uri="https://asia-northeast1-PROJECT.cloudfunctions.net/daily-report" \
  --http-method=POST \
  --oidc-service-account-email=scheduler-sa@PROJECT.iam.gserviceaccount.com \
  --oidc-token-audience="https://asia-northeast1-PROJECT.cloudfunctions.net/daily-report"

Pattern 2: Scheduler → Pub/Sub → Multiple Subscribers

# Pub/Sub Topic
gcloud pubsub topics create daily-trigger

# Scheduler → Pub/Sub
gcloud scheduler jobs create pubsub daily-trigger-job \
  --schedule="0 9 * * *" \
  --time-zone="Asia/Tokyo" \
  --topic=daily-trigger \
  --message-body="run"

# Subscriber 複数 (Fan-out)
gcloud pubsub subscriptions create report-sub --topic=daily-trigger \
  --push-endpoint=https://my-report-service.run.app
gcloud pubsub subscriptions create cleanup-sub --topic=daily-trigger \
  --push-endpoint=https://my-cleanup-service.run.app

Pattern 3: Scheduler → Cloud Run Job (Parallel Batch)

# Cloud Run Job (Python)
import os, sys
def main():
    task_index = int(os.environ.get("CLOUD_RUN_TASK_INDEX", 0))
    task_count = int(os.environ.get("CLOUD_RUN_TASK_COUNT", 1))
    # task_index に応じて担当範囲を処理
    print(f"Processing task {task_index}/{task_count}")

if __name__ == "__main__":
    main()

# Job 作成 (並列度 10)
gcloud run jobs create daily-batch-job \
  --image=asia-northeast1-docker.pkg.dev/PROJECT/repo/batch:v1 \
  --region=asia-northeast1 \
  --tasks=10 \
  --max-retries=3 \
  --task-timeout=3600

# Scheduler から Job 実行
gcloud scheduler jobs create http run-daily-batch \
  --schedule="0 2 * * *" \
  --time-zone="Asia/Tokyo" \
  --uri="https://asia-northeast1-run.googleapis.com/apis/run.googleapis.com/v1/namespaces/PROJECT/jobs/daily-batch-job:run" \
  --http-method=POST \
  --oauth-service-account-email=scheduler-sa@PROJECT.iam.gserviceaccount.com

Pattern 4: Scheduler → Workflows (Multi-step)

# Workflow YAML
main:
  steps:
    - extract:
        call: googleapis.cloudfunctions.v2.functions.call
        args: { name: projects/.../functions/extract }
        result: extract_result
    - transform:
        call: googleapis.cloudfunctions.v2.functions.call
        args: { name: projects/.../functions/transform }
        result: transform_result
    - load:
        call: googleapis.cloudfunctions.v2.functions.call
        args: { name: projects/.../functions/load }

# Workflow デプロイ
gcloud workflows deploy etl-workflow --source=etl.yaml --location=asia-northeast1

# Scheduler → Workflow
gcloud scheduler jobs create http etl-trigger \
  --schedule="0 3 * * *" \
  --uri="https://workflowexecutions.googleapis.com/v1/projects/PROJECT/locations/asia-northeast1/workflows/etl-workflow/executions" \
  --http-method=POST \
  --oauth-service-account-email=scheduler-sa@PROJECT.iam.gserviceaccount.com

Cron Format Cheat Sheet

cronMeaning
0 9 * * *Every day at 9am
0 0 * * 0Every Sunday at midnight
0 0 1 * *First day of every month at midnight
*/15 * * * *Every 15 minutes
0 9-17 * * 1-5Hourly from 9am to 5pm on weekdays

Retry and Error Handling

  • Scheduler auto-retry: up to 5 attempts with exponential backoff (5s to 1h)
  • Cloud Functions: messages retained for 7 days
  • Dead Letter Topic: forward failed messages to a separate topic
  • Cloud Monitoring alerts: notify PagerDuty on consecutive failures
  • Idempotent design: ensure the same job is safe to run multiple times

Typical Use Cases

  • Daily DB backups (Firestore Export / Cloud SQL Backup)
  • Scheduled report generation and Slack/Email delivery
  • Cache invalidation
  • SaaS data sync (Salesforce → BigQuery)
  • Shutting down idle resources (e.g. stopping VMs overnight)
  • Scheduled ML training (weekly continuous training)

What cron format does Cloud Scheduler use?

Standard Unix cron format (e.g. <code>0 9 * * *</code> = every day at 9am). Time zones are configurable (default UTC, Asia/Tokyo recommended for JP use cases).

How much does Cloud Scheduler cost?

The first 3 jobs are free, then $0.10 per job per month from the 4th. Executions are unlimited, so it stays cheap even at high frequencies.

Should I use Cloud Functions 2nd gen or Cloud Run?

Simple functions → Functions. Complex workloads → Cloud Run. For batch workloads, Cloud Run Jobs is also a strong option.

What are the execution time limits?

Cloud Functions 2nd gen: 60 min (HTTP and event). Cloud Run Job: up to 7 days. For long-running batch, use Cloud Run Job or GCE Batch.

How does retry on failure work?

Scheduler retries automatically (up to 5 times with exponential backoff). Cloud Functions retains messages for 7 days. Failed messages can be forwarded to a Pub/Sub Dead Letter Topic.

How is authentication handled?

Scheduler attaches an OIDC token (backed by a Service Account) to the target URL. Cloud Run / Functions enforce access with IAM (roles/run.invoker).

When should I choose Workflows instead?

Scheduler = single trigger. Workflows = multi-step orchestration. The realistic pattern is Scheduler → Workflows.

Cloud Run Job vs Cloud Functions for batch?

Cloud Run Job = container-based with task-level parallelism. Cloud Functions is a single invocation. Use Cloud Run Job for high-parallelism workloads.

Related articles: batch and automation

GCP Professional Cloud Developer (PCD) 完全ガイド|Cloud Run・GKE・CI/CD・APM

Google Cloud Professional Cloud Developer の試験範囲、Cloud Run / GKE / Cloud Build / Cloud Trace、AWS DVA / Azure AZ-204 比較、学習ロードマップを徹底解説。

Cloud Run 完全ガイド|サーバレス Container プラットフォームの全機能・料金・GKE 比較

Google Cloud Cloud Run の全機能ガイド。Service / Job、Autoscaling、コールドスタート対策、料金体系、GKE / Cloud Functions / App Engine との比較、認証・CI/CD 構成を解説。

GitHub Actions + GCP CI/CD 完全ガイド|Workload Identity・Cloud Run/GKE デプロイ (2026)

GitHub Actions で GCP CI/CD を構築する完全ガイド。Workload Identity Federation、setup-gcloud、Cloud Run / GKE デプロイ、Cloud Build 連携、Reusable Workflow、Self-hosted Runner、Secrets 管理を 2026 年最新版で網羅。

Google Cloud (GCP) 認定資格ロードマップ 2026 完全版|全 15 試験を体系化

Google Cloud 認定資格 全 15 試験 (Foundational 2 + Associate 3 + Professional 10) の 2026 年版ロードマップ。14/15 試験が日本語対応、Generative AI Leader (2025-05 新)・PMLE 2026-06 新版、AWS/Azure/GCP シェア比較、役割別ルートを日本語で整理。

※ Google Cloud is a trademark of Google LLC. For the latest details, see the official Cloud Scheduler documentation.

Check what you learned with practice questions

Practice with certification-focused question sets

Visit the GCP exam prep page
Author

NicheeLab Editorial Team

NicheeLab editorial team focused on data engineering and cloud certification learning. Content is structured around practical study needs and official exam domains.


Related articles
Google Cloud

Google Cloud Certification Roadmap (2026)

Choose your GCP certification path — Foundational, Associate...

Google Cloud

CDL Cloud Digital Leader: Complete Exam Guide (2026)

Pass the Cloud Digital Leader exam — cloud business value, G...

Google Cloud

GAIL Generative AI Leader: Complete Exam Guide (2026)

Pass the Generative AI Leader exam — Gemini, Vertex AI, Work...

Google Cloud

Vertex AI Fundamentals for GCP Certs (2026)

Vertex AI basics every cert candidate needs — Workbench, Pip...

Google Cloud

Associate Cloud Engineer (ACE): Complete Guide (2026)

Pass the Associate Cloud Engineer exam — Console, gcloud, pr...

Browse all Google Cloud articles (103)
© 2026 NicheeLab All rights reserved.