If you want to schedule functions to run at specified times, use the
firebase-functions/v2/scheduler
subpackage. The onSchedule
method creates a
Pub/Sub topic and uses
Cloud Scheduler to trigger events on
that topic, ensuring that your function runs on the desired schedule.
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 Platform 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 onSchedule
to start a Cloud Scheduler task.
For example, to clean up inactive user accounts once daily, you could use
something like the following:
// Run once a day at midnight, to clean up the users
// Manually run the task here https://console.cloud.google.com/cloudscheduler
exports.accountcleanup = onSchedule("every day 00:00", async (event) => {
// Fetch all user details.
const inactiveUsers = await getInactiveUsers();
// Use a pool so that we delete maximum `MAX_CONCURRENT` users in parallel.
const promisePool = new PromisePool(
() => deleteInactiveUser(inactiveUsers),
MAX_CONCURRENT,
);
await promisePool.start();
logger.log("User cleanup finished");
});
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 UTC
.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 GCP Console. The topic is named according to the following convention:
firebase-scheduled-function_name-region
For example:
firebase-scheduled-scheduledFunctionCrontab-us-east1.