If you run recurring maintenance on a server, you already know how fragile cron and crontab for beginners workflows can become: a single dead VM means missed backups, unsent reports, and silent failures. Cloud Scheduler is Google Cloud’s fully managed cron service — it fires HTTP, Pub/Sub, or App Engine targets on a schedule you define, with automatic retries, time-zone support, and no server to babysit. Paired with Cloud Functions, it gives you serverless cron jobs that scale to zero when idle and cost almost nothing when they run.
In this guide, you will deploy a real example: a Cloud Function that cleans up old files, triggered every night by Cloud Scheduler. Along the way you will learn the gcloud commands, secure the invocation with OIDC, configure retries, and monitor every run in Cloud Logging. The same pattern works for nightly database dumps, certificate renewals, invoice generation, or any batch job you currently run from a crontab.
Prerequisites for Using Cloud Scheduler – Schedule Serverless Cron Jobs with Cloud
Before you start, make sure you have the following in place:
- A Google Cloud project with billing enabled.
- The gcloud CLI installed and authenticated (
gcloud auth loginandgcloud config set project PROJECT_ID). - The
roles/cloudscheduler.adminandroles/cloudfunctions.developerIAM roles on your account. - Basic familiarity with deploying containers on Google Cloud Run concepts — Cloud Functions (2nd gen) run on the same underlying infrastructure.
You will enable three APIs in Step 1, so no prior API setup is required.
Step 1: Enable the Required APIs – Schedule Serverless Cron Jobs with Cloud
Cloud Scheduler needs the Cloud Scheduler API, the Cloud Functions API, and the Cloud Build API (used to build the function’s container image). Enable all three with one command:
gcloud services enable \
cloudscheduler.googleapis.com \
cloudfunctions.googleapis.com \
cloudbuild.googleapis.com
Wait for the operation to complete. Enabling APIs can take a minute or two; the command exits when all three are active.
Step 2: Deploy the Cloud Function
Create a working directory and write a small HTTP function. This example, written in Python, logs the time it ran and returns a success message — a placeholder you can replace with real cleanup logic:
mkdir -p ~/scheduler-demo && cd ~/scheduler-demo
cat > main.py << 'EOF'
import functions_framework
import datetime
@functions_framework.http
def nightly_cleanup(request):
now = datetime.datetime.now(datetime.timezone.utc).isoformat()
# TODO: put your real job here (purge temp files, rotate logs, ...)
print(f"[nightly-cleanup] running at {now}")
return ({"status": "ok", "ran_at": now}, 200)
EOF
cat > requirements.txt << 'EOF'
functions-framework==3.*
EOF
Deploy the function as an HTTP-triggered Cloud Function (2nd gen). Replace REGION with a region close to you, such as us-central1 or asia-southeast1:
gcloud functions deploy nightly-cleanup \
--gen2 \
--region=REGION \
--runtime=python312 \
--source=. \
--entry-point=nightly_cleanup \
--trigger-http \
--allow-unauthenticated \
--memory=256Mi \
--timeout=300s
Note the --allow-unauthenticated flag: we will lock this down in Step 4 by requiring an OIDC token that only Cloud Scheduler can mint. For the first test, open access keeps troubleshooting simple.
Capture the function’s HTTPS URL — you will need it for the scheduler job:
gcloud functions describe nightly-cleanup \
--gen2 --region=REGION \
--format='value(serviceConfig.uri)'
Step 3: Create the Cloud Scheduler Job
Now create a Cloud Scheduler job that calls the function every night at 02:30 in your local time zone. The schedule uses standard cron syntax (minute hour day month weekday):
gcloud scheduler jobs create http nightly-cleanup-job \
--location=REGION \
--schedule="30 2 * * *" \
--time-zone="Asia/Ho_Chi_Minh" \
--uri="https://REGION-PROJECT_ID.cloudfunctions.net/nightly-cleanup" \
--http-method=POST \
--headers="Content-Type=application/json" \
--message-body='{"trigger":"scheduler"}'
Key flags explained:
--schedule: cron expression."30 2 * * *"means 02:30 every day. Use"*/10 * * * *"for every 10 minutes during testing.--time-zone: IANA time-zone name. Cloud Scheduler handles daylight-saving transitions correctly, unlike a raw crontab.--uri: the function’s HTTPS URL from Step 2.--message-body: optional JSON payload your function can read from the request.
Step 4: Secure the Function with OIDC
Leaving the function public means anyone can trigger it. The proper pattern is: remove public access and let the scheduler authenticate with an OIDC token minted from a dedicated service account.
First, create a service account for the scheduler:
gcloud iam service-accounts create scheduler-invoker \
--display-name="Cloud Scheduler invoker"
SA_EMAIL="scheduler-invoker@PROJECT_ID.iam.gserviceaccount.com"
gcloud functions add-invoker-policy-binding nightly-cleanup \
--gen2 --region=REGION \
--member="serviceAccount:${SA_EMAIL}" \
--role="roles/cloudfunctions.invoker"
Then remove public access and update the job to attach the OIDC token:
gcloud functions remove-invoker-policy-binding nightly-cleanup \
--gen2 --region=REGION \
--member="allUsers" \
--role="roles/cloudfunctions.invoker"
gcloud scheduler jobs update http nightly-cleanup-job \
--location=REGION \
--oidc-service-account-email="${SA_EMAIL}" \
--oidc-token-audience="https://REGION-PROJECT_ID.cloudfunctions.net/nightly-cleanup"
From now on, only invocations carrying a valid OIDC token from scheduler-invoker can reach your function.
Step 5: Test the Schedule Manually
Do not wait until 02:30 to discover a typo. Trigger the job on demand and watch it run:
gcloud scheduler jobs run nightly-cleanup-job --location=REGION
Check the last run’s status and the function’s logs:
gcloud scheduler jobs describe nightly-cleanup-job \
--location=REGION \
--format='table(name,schedule,state,lastAttemptTime)'
gcloud functions logs read nightly-cleanup \
--gen2 --region=REGION --limit=20
You should see a lastAttemptTime of a few seconds ago and your [nightly-cleanup] running at ... line in the function logs. If the function returned an HTTP 200, the job is healthy.
Step 6: Configure Retries and Deadlines
Production cron jobs must survive transient failures. the scheduler retries failed attempts automatically; tune the policy when you create or update the job:
gcloud scheduler jobs update http nightly-cleanup-job \
--location=REGION \
--max-retry-attempts=5 \
--max-retry-duration=30m \
--min-backoff-duration=30s \
--max-backoff-duration=5m \
--attempt-deadline=10m
For critical jobs, add a dead-letter topic so permanently failing runs land in Pub/Sub for alerting:
gcloud pubsub topics create scheduler-dead-letter
gcloud scheduler jobs update http nightly-cleanup-job \
--location=REGION \
--dead-letter-topic="projects/PROJECT_ID/topics/scheduler-dead-letter"
Step 7: Monitor Runs in Cloud Logging
Every execution writes structured logs. Query them to build dashboards or alerts:
gcloud logging read \
'resource.type="cloud_scheduler_job" AND resource.labels.job_id="nightly-cleanup-job"' \
--limit=10 --format=json | \
python3 -c "import json,sys; [print(e['timestamp'], e.get('severity'), e.get('textPayload','')) for e in json.load(sys.stdin)]"
In the Cloud Console, go to Cloud Scheduler, click the job, and check the Logs tab — each attempt shows its HTTP status code and latency. Set up a log-based alert on non-2xx statuses so you hear about failures before your users do.

Cloud Scheduler vs. Traditional Cron: When to Use Which
the service wins when the job is event-driven, needs retries, or must run without a dedicated VM — the classic serverless cron scenario. Keep a traditional crontab on a VM when the job needs local files, long runtimes beyond Cloud Functions limits (up to 60 minutes on 2nd gen, 9 on 1st gen), or must run inside a VPC without a connector.
A hybrid pattern is common: the scheduler fires a Pub/Sub message, and a subscriber on a VM or GKE pod does the heavy lifting. You get managed scheduling with arbitrary compute behind it.
Troubleshooting Common Scheduling Issues
Job shows FAILED with HTTP 403
The function’s IAM policy rejects the caller. Verify the service account email on the job matches the one granted roles/cloudfunctions.invoker, and that --oidc-token-audience equals the function’s exact URL.
Job shows FAILED with HTTP 404
The --uri is wrong — usually a mistyped region or function name. Re-run the gcloud functions describe command from Step 2 and update the job with the exact URL.
Runs happen at the wrong time
Check --time-zone: it must be an IANA name like Asia/Ho_Chi_Minh. gcloud scheduler jobs describe shows the configured schedule and time zone. Remember that cron * fields and DST transitions can surprise you — always test with a short interval first.
Function times out
Raise the timeout with gcloud functions deploy ... --timeout=540s (2nd gen maximum is 3600s) and make sure the job’s --attempt-deadline is longer than the function’s timeout.
Duplicate executions
Cloud Scheduler guarantees at-least-once delivery. Make your function idempotent — check whether the work was already done before doing it again.
Conclusion
the managed scheduler turns fragile VM-based cron into a managed, observable, serverless workflow: define the schedule, point it at a Cloud Function or any HTTP endpoint, secure it with OIDC, and let Google handle retries, time zones, and logging. The seven steps above give you a production-ready template — swap in your own function logic and you have nightly backups, report generation, or cache warming with no server to patch.
For deeper reading, see the Google Cloud Scheduler documentation for quotas, Pub/Sub targets, and App Engine targets. And if your workload outgrows functions, the same scheduling skills transfer directly when you deploy containers on Google Cloud Run.