Introduction
When you need to run code periodically, Cloud Functions for Firebase can help. It’s handy for tasks that must run at fixed times.
Use cases
- Aggregate Firestore user data once per day
- Delete obsolete data
How it works
Internally, the cron service Cloud Scheduler publishes a message to a Pub/Sub topic. A Cloud Function subscribes to that topic to schedule execution.
Installation
Switch to the Blaze plan
This isn’t available on the free plan; switch to the pay‑as‑you‑go Blaze plan.
Install tools
$ npm install -g firebase-tools
Log in:
$ firebase login
Initialize:
$ firebase init functions
Writing functions
To set a region, use functions.region
. Example that runs every minute:
Intervals are specified using either the cron schedule format or the App Engine cron format.
exports.scheduledFunction = functions.region('asia-northeast1')
.pubsub.schedule('every 1 minutes')
.timeZone('Asia/Tokyo')
.onRun(() => {
console.info('hello world');
});
Deploy:
$ firebase deploy --only functions
After deployment, the scheduled job appears under Functions as shown below.
