Search Lessons, Code Snippets, and Videos
search by algolia
X
#native_cta# #native_desc# Sponsored by #native_company#

Cloud Scheduler for Firebase Functions

Episode 148 written by Jeff Delaney
full courses and content on fireship.io

Health Check: This lesson was last reviewed on and tested with these packages:

  • twilio v3.x
  • functions v2.x

Find an issue? Let's fix it

Source code for Cloud Scheduler for Firebase Functions on Github

Firebase developers commonly get stuck asking the question How do I trigger a Cloud Function to run ax X time, or every X time intervals. In the past, the best way to handle this requirement was to use a service like cron-job.org to hit an HTTP endpoint, or deploy your own node app to app engine - both options were not ideal. Thankfully, Google launched the Cloud Scheduler in November 2018 to make this time triggers for cloud functions much, much easier.

Setup a Scheduled Cloud Function Task

I highly recommend using a Pub/Sub trigger for scheduled functions over HTTP because they provide secure authentication out of the box. They are also easier to work with when communicating between multiple GCP services.

A scheduled job simply sends a data payload to an HTTP endpoint or Pub/Sub channel based on the schedule you provide it (1 minute of granularity). The tricky part is defining the schedule as a cron table. You could spend some time learning crontab, but the smarter approach is to use a tool like Crontab Guru to build your scheduler.

Let’s look at the entire process step-by-step for building a time-based trigger for a cloud function.

  1. Deploy a Cloud Function (HTTP or Pub/Sub).
  2. Go to the Pub/Sub tab on the GCP console and create your topic.
  3. Define a cron schedule with crontab.guru.
  4. Go to the Cloud Scheduler tab and create your task.

Robo-Caller Cloud Function

Below is an example of a Pub/Sub cloud function that uses the Twilio Programmable Voice API to make calls to a phone number.

import * as functions from 'firebase-functions';
const { to, from, sid, auth } = functions.config().twilio;
import * as twilio from 'twilio';
const client = twilio(sid, auth);

export const callme = functions.pubsub
.topic('callme')
.onPublish(async message => {
const call = await client.calls.create({
to,
from,
url: 'URL to your TwiML script',
method: 'GET'
});

console.log(call.toJSON());

return call.sid;
});