If you want to schedule functions to run at specified times, use
the onSchedule
handler to create a
Pub/Sub topic that uses
Cloud Scheduler to trigger events on
that topic.
Before you begin
To use this solution in your Firebase project, your project must be on the Blaze pricing plan. If it's not already on the Blaze plan, upgrade your pricing plan.
Though billing is required, you can expect the overall cost to be manageable, as each Cloud Scheduler job costs $0.10 (USD) per month, and there is an allowance of three jobs per Google account, at no charge. Use the Blaze pricing calculator to generate a cost estimate based on your projected usage.
The Pub/Sub and Cloud Scheduler APIs must be enabled for your project. These should already be enabled for most Firebase projects; you can verify in the Google Cloud console.
Write a scheduled function
In Cloud Functions for Firebase, scheduling logic resides in your functions code,
with no special deploy-time requirements. To create a scheduled function,
use functions.pubsub.schedule('your schedule').onRun((context))
.
For example, to run a function every
five minutes with
App Engine cron.yaml
syntax, do something like this:
exports.scheduledFunction = functions.pubsub.schedule('every 5 minutes').onRun((context) => {
console.log('This will be run every 5 minutes!');
return null;
});
Both Unix Crontab and App Engine syntax are supported by Cloud Scheduler. For example, to use Crontab to select a specific timezone in which to run a scheduled function, do something like this:
exports.scheduledFunctionCrontab = functions.pubsub.schedule('5 11 * * *')
.timeZone('America/New_York') // Users can choose timezone - default is America/Los_Angeles
.onRun((context) => {
console.log('This will be run every day at 11:05 AM Eastern!');
return null;
});
The value for timeZone
must be a time zone name from the
tz database. See the
Cloud Scheduler reference
for more information on supported properties.
Deploy a scheduled function
When you deploy a scheduled function, the related scheduler job and pub/sub topic are created automatically. The Firebase CLI echoes the topic name, and you can view the job and topic in the Google Cloud console. The topic is named according to the following convention:
firebase-scheduled-function_name-region
For example:
firebase-scheduled-scheduledFunctionCrontab-us-east1.