Firebase Cloud Functions: Schedule Reoccurring Functions Natively

Paul Halliday

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:

# Create and navigate to a new directory
$ mkdir cloud-functions-schedule && cd cloud-functions-schedule

# Create an app file
$ touch index.js

# Initialise a new Node project with defaults
$ npm init -y

# Install the Firebase-tools globally
$ npm i firebase-tools -g

# Log into Firebase
$ firebase login

# Initialise Firebase Cloud Functions
$ firebase init

> Scroll down to "functions" and hit the space bar to enable it
> Hit enter to activate this
> Select your Firebase project (or create a new one)
> Select TypeScript or JavaScript
> Install npm dependencies

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! :)

  Tweet It

🕵 Search Results

🔎 Searching...

Sponsored by #native_company# — Learn More
#native_title# #native_desc#
#native_cta#