Timing Cloud Functions for Firebase using an HTTP Trigger and Cron - Firecasts

By: Firebase

233   6   10546

Uploaded on 06/29/2017

Scheduling Cron Jobs with an App Engine: https://goo.gl/Nqg3DW
Functions Samples: https://goo.gl/C2FdYs
Nodemailer documentation: https://goo.gl/uRjWP1
Firecast on Cloud Storage Triggers - shows using Firebase Admin SDK: https://goo.gl/Z8dRVA
Configuring your environment: https://goo.gl/ukYHkW
Sending Email from an Instance: https://goo.gl/nO9wA7
Firebase Admin SDK Documentation: https://goo.gl/7z1yiX

Cloud Functions for Firebase lets you run managed backend code for your mobile app that extends and connects Firebase features. In this Firecast, Jen will show you how to write functions that run on a timed schedule.

Add the Firecasts playlist! https://goo.gl/n2XqG1
Subscribe to the Firebase Channel: https://goo.gl/9giPHG
Music by http://terramonk.com

Comments (14):

By anonymous    2017-09-20

It looks like you're trying to put a Realtime Database trigger inside your HTTP trigger, which won't have the outcome you're looking for. Instead of using a database trigger, use the Firebase Admin SDK to access the database from within the HTTP trigger.

In your code, add

const admin = require('firebase-admin');
const ref = admin.database().ref();

And use ref to access the database.

Check out the Admin SDK documentation here.

Here are some samples of Cloud Functions, some of which show the Admin SDK.

Here's a video showing how to use the Admin SDK

Here's a video on timing Cloud Functions

Original Thread

By anonymous    2017-09-20

You can use cronjobs. Watch this video for getting started
Timing Cloud Functions for Firebase using an HTTP Trigger and Cron - Firecasts

Original Thread

By anonymous    2017-09-20

Instead of using a Database trigger, use an HTTP trigger with a third party cron job service. Check out these resources to learn more:

Timing Cloud Functions with HTTP Triggers and Cron

Cloud Functions Samples - Delete Unused Accounts Cron

Original Thread

By anonymous    2017-10-30


Original Thread

By anonymous    2017-11-06

Firebase doesn't support cron jobs or scheduled tasks. You need to use a third party system to trigger a clean up function.

The function itself would be fairly easy to write, you could just do a query on any value older than 24 hours then delete it.

The Firebase team did a great video on how to setup cron jobs which would work in your scenario.


Original Thread

By anonymous    2017-11-13

I have now fully worked this out. Through extensive research and a lot of help here on Stackoverflow i managed to solve this.

so, these are my findings:

  1. You DO need to send your private keys to your firebase functions when minting a Firebase Token. In the Firebase console, you can extract the key and rename the file to service-account.json. This should be put in your Functions folder before performing your Firebase deploy
  2. In your index.js file, you can get your service file by entering this code:

    const admin = require('firebase-admin');
    const serviceAccount = require('./service-account.json');
      credential: admin.credential.cert(serviceAccount)
  3. Write the function for accepting information from the other Authentication service:

    // Create a Firebase token from any UID
    exports.createFirebaseToken = functions.https.onRequest((req, res) => {
      // The UID and other things we'll assign to the user.
      const uid = req.body.uid;
      const additionalClaims = {
        name: req.body.name,
        email: req.body.email
      // Create or update the user account.
      const userCreationTask = admin.auth().updateUser(uid, additionalClaims).catch(error => {
        if (req.method === 'PUT') {
        if (req.method === 'GET') {
         res.status(403).send('Please use POST for this function');
        // If user does not exists we create it.
        if (error.code === 'auth/user-not-found') {
          console.log(`Created user with UID:${uid}, Name: ${additionalClaims.name} and e-mail: ${additionalClaims.email}`);
          return admin.auth().createUser({
          uid: uid,
          displayName: additionalClaims.name,
          email: additionalClaims.email,
            throw error;
        return Promise.all([userCreationTask]).then(() => {
          console.log('Function create token triggered');
          // Create a Firebase custom auth token.
          admin.auth().createCustomToken(uid, additionalClaims).then((token) => {
          console.log('Created Custom token for UID "', uid, '" Token:', token);
            return token

It's very important to respond with a res.status since this will finish the task. A single return statement will not do this. A fully working sample from Firebase themself can be found on github

  1. You can now make a HTTP-request that could look something like this using Alamofire and swift

    Alamofire.request("https://us-central1-<YOUR DATABASE REFERENCE>.cloudfunctions.net/createFirebaseToken", 
    method: .post, parameters: parameters, encoding: JSONEncoding.default).
    responseString(completionHandler: { (token) in
        // Handle the result here

    In this case, the Parameters is a regular JSON file that contains whatever you want to add to the users Firebase account.

  2. IMPORTANT Anyone with your cloudfunctions URL can trigger this token minting. So make sure you add security measures to handle this. This is briefly mentioned in a Firecast video on youtube made by Firebase

  3. When your client received the token you a custom auth sign in iOS or in Android as described in the documentation.

  4. You are now authenticated both towards Firebase and Microsoft

  5. I have also added an extra layer of security, by checking that the ID i got from Microsoft, is the same ID stored in the authenticated account from Firebase.

Original Thread

By anonymous    2017-11-13

There is no such built-in functionality.

The easiest way to build it yourself is by:

  1. Adding a expirationTimestamp property to your documents.
  2. Denying read of documents whose expiration has passed in your security rules.

    match /collection/{document} {
      allow read: if resource.data.expirationTimestamp > request.time.date();

    Unfortunately this means that you won't be able to query the collection anymore. You'll need to access the individual documents.

  3. Periodically run Cloud Functions code to delete expired documents.

Original Thread

By anonymous    2017-11-20

There is no way in which you can add something to ServerValue.TIMESTAMP. This represents the timestamp of the server that is added at a specific moment to your database and cannot be increased or decreased. To achieve what you want, i recomand you write a Cloud Function. For this i recomand read this post from the Firebase blog: How to Schedule (Cron) Jobs with Cloud Functions for Firebase, see this video from youtube, Timing Cloud Functions for Firebase using an HTTP Trigger and Cron - Firecasts and see this samples from functions-samples repo.

Original Thread

By anonymous    2017-11-27

You will need to use a cron job to trigger a Firebase cloud function. see [Firebase Cron](https://www.youtube.com/watch?v=CbE2PzvAMxA). It took a single search here to find dozens of links on how to accomplish this task so this question is a duplicate.

Original Thread

By anonymous    2017-11-27

If you are comfortable using Python, then read this post ->

How to Schedule (Cron) Jobs with Cloud Functions for Firebase to create some Firebase cloud functions

My suggestion would be to use the daily-tick function to scan through your Firebase realtime database to retrieve all the books that are "due the next day's date" and issue notifications to them.

It should meet your requirement in a pretty straightforward way. Alternatively, you may try a different method as suggested in the Firebase video here Timing Cloud Functions for Firebase using an HTTP Trigger and Cron - Firecasts

Let me know if neither of these meet your requirements. And what am I missing. I will be glad to recommend a better alternative based on your feedback

Original Thread

By anonymous    2017-12-18

Your best bet (currently) is to set up a recurring job to periodically sweep entries out of your database. You can do this with Cloud Functions for Firebase and a scheduling mechanism you provide. There is a blog and video about this.

I suggesting storing the time to delete as an abosolute date in time (like System.currenTimeMillis()) rather than as a delay so you can query the database for everything that ought to be deleted at this moment.

Original Thread

Recommended Books

    Submit Your Video

    If you have some great dev videos to share, please fill out this form.