Updated Nov 25, 20267 min read

Run Cron Jobs on Google Cloud Without Terraform

What a scheduled job on Google Cloud usually takes, from Cloud Scheduler and Cloud Run to service accounts, OIDC tokens and run.invoker grants, what the Terraform looks like, and how to run the same schedules in your own GCP project from cron jobs declared in code.

Illustration for Run Cron Jobs on Google Cloud Without Terraform

A scheduled job on Google Cloud is usually a Cloud Scheduler job that calls a Cloud Run service on a cron expression, such as a nightly cleanup or an hourly usage rollup.

Each job also needs a service account, a run.invoker grant on the target and an OIDC token with the right audience, plus retries and a time zone. This guide lists those pieces, shows the Terraform and then runs the same jobs from code.

What does a Cloud Scheduler job need?

PieceWhy it is needed
A Cloud Run service or jobRuns the code; a service is called over HTTP, a job is started through the Cloud Run Admin API
A service account for the schedulerThe identity that signs each request
roles/run.invoker on the targetLets that identity call the private service or execute the job
The Cloud Scheduler jobSchedule, time zone, target URL, HTTP method and body
An OIDC token with the right audienceCloud Run rejects calls whose token audience does not match
Retry and deadline settingsHow often and how long the scheduler retries a failed run
An idempotent endpointA retried or overlapping run must not do the work twice

Google documents the service account and token setup in its guide to authenticating HTTP targets, and the Cloud Run guide to running services on a schedule adds the invoker grant. Cloud Scheduler bills $0.10 per job for every 31 days, with 3 free jobs per billing account, per its pricing page.

What does the Terraform look like?

For one job against an existing private Cloud Run service, the Terraform creates the service account, the invoker binding and the scheduler job, and each extra job repeats the last block. This configuration passes terraform validate with Terraform 1.13 and the hashicorp/google provider 8.12:

# scheduler.tf variable "project_id" { type = string } variable "region" { type = string default = "europe-west1" } variable "service_name" { type = string default = "billing" } # The identity Cloud Scheduler uses to sign its requests. resource "google_service_account" "scheduler" { account_id = "billing-scheduler" display_name = "Cloud Scheduler for the billing service" } # Lets that identity call the private Cloud Run service, and nothing else. resource "google_cloud_run_v2_service_iam_member" "scheduler_invoker" { project = var.project_id location = var.region name = var.service_name role = "roles/run.invoker" member = "serviceAccount:${google_service_account.scheduler.email}" } data "google_cloud_run_v2_service" "billing" { project = var.project_id location = var.region name = var.service_name } resource "google_cloud_scheduler_job" "expire_trials" { name = "expire-trials" region = var.region schedule = "0 3 * * *" time_zone = "Etc/UTC" attempt_deadline = "320s" retry_config { retry_count = 3 } http_target { http_method = "POST" uri = "${data.google_cloud_run_v2_service.billing.uri}/internal/expire-trials" oidc_token { service_account_email = google_service_account.scheduler.email audience = data.google_cloud_run_v2_service.billing.uri } } }

The audience has to be the service URL, the scheduler retries a failed run up to retry_count times, and google_cloud_scheduler_job lists further options such as backoff limits. The endpoint behind /internal/expire-trials still has to check the token, stay idempotent and be testable locally, which none of the configuration helps with.

The gcloud scheduler jobs create http command builds the same job from a script, and clicking through the console works once, but both leave the service account and grants to be repeated for staging and production by hand.

How does Encore run cron jobs on Google Cloud?

Encore brings infrastructure from code, so a cron job is a CronJob declared next to the endpoint it calls, and on a deployed environment Encore calls that endpoint on schedule with signed requests and no extra infrastructure, as the GCP infrastructure docs describe. There is no Cloud Scheduler job, scheduler service account or invoker binding to manage, and the Postgres database the jobs use becomes Cloud SQL in your own project.

Application code passes through Encore and infrastructure guardrails to resources provisioned in your own AWS or GCP account.

Set up the app

Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

~
$ encore app create saas --example=ts/hello-world$ cd saas && mkdir billing

Declare the jobs next to their endpoints

The billing service has a daily job that expires trials and an hourly rollup of usage. The folder also has an encore.service.ts that exports new Service("billing"):

// billing/jobs.ts import { api } from "encore.dev/api"; import { SQLDatabase } from "encore.dev/storage/sqldb"; import { CronJob } from "encore.dev/cron"; import log from "encore.dev/log"; const db = new SQLDatabase("billing", { migrations: "./migrations" }); // Moves workspaces whose trial has ended to the free plan. // Running it twice changes nothing, because only active trials match. export const expireTrials = api({ expose: false }, async (): Promise<{ expired: number }> => { let expired = 0; const rows = db.query<{ id: number }>` UPDATE workspaces SET plan = 'free', trial_ends_at = NULL WHERE plan = 'trial' AND trial_ends_at <= now() RETURNING id`; for await (const row of rows) { expired++; log.info("trial expired", { workspaceId: row.id }); } return { expired }; }); const _ = new CronJob("expire-trials", { title: "Expire ended trials", schedule: "0 3 * * *", // 03:00 UTC every day endpoint: expireTrials, }); // Recomputes the last three full hours of usage, so a missed or repeated run // overwrites the same rows instead of double counting. export const rollupUsage = api({ expose: false }, async (): Promise<{ rows: number }> => { const result = await db.queryRow<{ n: number }>` WITH hours AS ( SELECT generate_series( date_trunc('hour', now()) - interval '3 hours', date_trunc('hour', now()) - interval '1 hour', interval '1 hour') AS start ), upserted AS ( INSERT INTO usage_hourly (workspace_id, hour_start, events) SELECT e.workspace_id, h.start, count(*) FROM hours h JOIN usage_events e ON e.created_at >= h.start AND e.created_at < h.start + interval '1 hour' GROUP BY e.workspace_id, h.start ON CONFLICT (workspace_id, hour_start) DO UPDATE SET events = EXCLUDED.events RETURNING 1 ) SELECT count(*)::int AS n FROM upserted`; return { rows: result?.n ?? 0 }; }); const _rollup = new CronJob("rollup-usage", { title: "Roll up hourly usage", every: "1h", endpoint: rollupUsage, });
-- billing/migrations/1_create_billing.up.sql CREATE TABLE workspaces ( id BIGSERIAL PRIMARY KEY, name TEXT NOT NULL, plan TEXT NOT NULL CHECK (plan IN ('trial', 'free', 'pro')), trial_ends_at TIMESTAMPTZ ); CREATE TABLE usage_events ( id BIGSERIAL PRIMARY KEY, workspace_id BIGINT NOT NULL REFERENCES workspaces (id), created_at TIMESTAMPTZ NOT NULL DEFAULT now() ); CREATE INDEX usage_events_by_time ON usage_events (created_at); CREATE TABLE usage_hourly ( workspace_id BIGINT NOT NULL REFERENCES workspaces (id), hour_start TIMESTAMPTZ NOT NULL, events BIGINT NOT NULL, PRIMARY KEY (workspace_id, hour_start) );

Cron jobs do not run under encore run or in preview environments, so locally you call expireTrials and rollupUsage from the local development dashboard or a test, with Postgres started by encore run, and check the rows they change. The cron docs explain the rules that keep schedules predictable: an every interval must divide 24 hours evenly, schedules run in UTC, and the endpoint takes no parameters and must be idempotent, which is why both jobs above are written so a second run changes nothing.

To deploy, connect your GCP project as described in Connect your cloud account and push. The jobs then appear in the Encore dashboard with each run and its result, next to the traces of the endpoint calls.

A coding agent asked to add a weekly report writes another CronJob and its endpoint in the same file, and can check the report locally by calling the endpoint, with no scheduler resource or grant to add elsewhere.

Best fit: Teams on Google Cloud that want scheduled work defined in the service that does it, with Cloud SQL and the rest of the backend in their own GCP project.

Which approach should you use?

Use Cloud Scheduler with Terraform when the jobs call systems outside your application, such as Cloud Run jobs owned by a data team, or when a platform team manages schedules centrally. Use Encore when the schedules belong to the application, and you want each job reviewed and shipped together with the endpoint it runs.

Frequently asked questions

How do I run a cron job on Google Cloud?

The usual setup is a Cloud Scheduler job with an HTTP target that calls a Cloud Run service or starts a Cloud Run job on a cron schedule. The scheduler signs each request with an OIDC token for a service account that has roles/run.invoker on the target, so the endpoint can stay private.

How much does Cloud Scheduler cost?

Cloud Scheduler bills $0.10 per job for each 31 days the job exists, and each billing account gets 3 jobs a month free, according to the Cloud Scheduler pricing page. The Cloud Run time the job uses is billed separately.

Why does my Cloud Scheduler job return 401 or 403?

Usually the scheduler's service account is missing roles/run.invoker on the Cloud Run service, the job sends no OIDC token, or the token's audience does not match the service URL. Check the job's last attempt in Cloud Logging, which records the HTTP status the target returned.

How do I run cron jobs in my own GCP project without Terraform?

With Encore you declare each job with new CronJob next to the endpoint it calls, and deploying to your GCP project runs the schedule, with no scheduler job, service account or IAM binding for you to configure. Cron jobs do not run under encore run, so you test them locally by calling the endpoint directly.

Deploy to your cloud on AWS and Google Cloud
without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders