If you’ve ever wanted to run a Firebase Cloud Function every X minutes, hours or days, you’ll have ran into the
cron job pattern before. It’s an effective way to schedule a task on a particular frequency, but there hasn’t been a way to do this from within the Firebase SDK until very recently.
In this article, we’ll be investigating how to do this with a new Firebase Cloud Functions project using Node.js. As always, we’ll be starting out with a brand new project:
— Sorry to interrupt this program! 📺
If you're interested in learning Node in a comprehensive and structured way, I highly recommend you try Wes Bos' Learn Node course. Learning from a premium course like that is a serious investment in yourself.
Plus, this is an affiliate link, so if you purchase the course you help Alligator.io continue to exist at the same time! 🙏
Great! We’ve now got a standard Firebase Cloud Functions project up and running. We’ll use this to log a message to the console:
const functions = require('firebase-functions'); export const scheduledCron = functions.pubsub.schedule('40 9 * * *') .onRun(context => console.log('Hello at 9:40 from scheduler!')); export const scheduledEnglishTimer = functions.pubsub.schedule('every 10 minutes').onRun(context => console.log('Hello every 10 minutes!'))
Notice how we’re able to use two separate syntax for this. One is using the
cron style and one uses plain English. Both work, so I’d recommend using whatever you’re most comfortable with.
You will need to be on the Blaze plan and above for this as it uses the Google Cloud Scheduler with a maximum of three free Scheduler jobs on the go at any one time.
The cost for running a Scheduler job costs $0.10 a month and the other costs similar to that should be the same as running any other Cloud Function.
As always, when billing is concerned - do your research! :)