How to Use Scheduled Functions in Firebase
Use
firebase-functions with pubsub.schedule() to create scheduled functions in Firebase. Deploy them with firebase deploy --only functions and they run automatically at set times.Syntax
The basic syntax to create a scheduled function in Firebase uses functions.pubsub.schedule(). You specify a cron schedule string and then define the function to run on that schedule.
Parts explained:
functions.pubsub.schedule('cron'): Sets the timing using a cron expression or predefined schedule..onRun(callback): Defines the function that runs on schedule.callback: The code to execute when the function triggers.
javascript
const functions = require('firebase-functions'); exports.scheduledFunction = functions.pubsub.schedule('every 5 minutes').onRun((context) => { console.log('This runs every 5 minutes!'); return null; });
Example
This example shows a scheduled function that runs every day at midnight UTC and logs a message. It demonstrates how to set up the schedule and the function code.
javascript
const functions = require('firebase-functions'); exports.dailyJob = functions.pubsub.schedule('0 0 * * *').onRun((context) => { console.log('Daily job executed at midnight UTC'); return null; });
Output
Daily job executed at midnight UTC
Common Pitfalls
Common mistakes when using scheduled functions in Firebase include:
- Not enabling the Cloud Scheduler API in your Google Cloud project.
- Using incorrect cron syntax or time zones.
- Forgetting to deploy functions after changes.
- Not returning a promise or null in the function, which can cause unexpected behavior.
Always check logs in Firebase Console to debug scheduling issues.
javascript
/* Wrong: Missing return causes function to hang */ exports.badScheduledFunction = functions.pubsub.schedule('every 10 minutes').onRun(() => { console.log('This might cause issues'); // No return statement }); /* Right: Return null to signal completion */ exports.goodScheduledFunction = functions.pubsub.schedule('every 10 minutes').onRun(() => { console.log('This runs correctly every 10 minutes'); return null; });
Quick Reference
| Feature | Description | Example |
|---|---|---|
| Schedule | Set timing using cron or presets | 'every 5 minutes', '0 0 * * *' |
| Function trigger | Define code to run on schedule | .onRun((context) => { ... }) |
| Return value | Return null or a promise | return null; |
| Deploy command | Deploy functions to Firebase | firebase deploy --only functions |
Key Takeaways
Use functions.pubsub.schedule() with .onRun() to create scheduled Firebase functions.
Always return null or a promise in your scheduled function to signal completion.
Enable Cloud Scheduler API in your Google Cloud project before deploying.
Use correct cron syntax and verify time zones for accurate scheduling.
Deploy changes with 'firebase deploy --only functions' to activate schedules.