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 (18):

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');
admin.initializeApp(functions.config().firebase);
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

https://www.youtube.com/watch?v=CbE2PzvAMxA

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.

https://www.youtube.com/watch?v=CbE2PzvAMxA

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');
    admin.initializeApp({
      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') {
          res.status(403).send('Forbidden!');
        }
    
        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;
            console.log('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);
            res.status(200).send(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

By anonymous    2018-02-12

Depends on the scope of your project.

  • If your project is only gonna be for 1 type of mobile client, for example, is only Android. Then set the alarms on the device, and use the Firebase database as data persistence for the user to have a flawless experience between installs and devices.

  • If your project also has to be for web, and send emails along with the notification, then you will have to schedule a cron job. The only question here is how accurate the alarms have to be. This is the important detail because if the alarms need to be exact, you are gonna have to schedule one cronjob each minute, incredibly wasteful, querying the database so often will consume your usage quota pretty fast. Besides, mobile devices have energy saving modes during the meanwhile are not completely active so push notifications can be delayed by the system until the next maintenance window. My recommendation would be to narrow down the alarm to a 30 or 15 minutes window. So you can schedule cronjobs that will query the database for objects in that span of time.

    1. For scheduling a cron job I recommend you the next official video

    2. For sending the push notification using FCM I recommend checking the Functions samples on Github

    3. The best for starting with Functions is this video

    4. And for your database structure, please see example below

{
  "user_alarms": {
    "uid1": {
      "pushkey1": {
        "full_object": "goes here"
      },
      "pushkey2": {
        "full_object": "goes here"
      }
    },
    "uid2": {
      "pushkey3": {
        "full_object": "goes here"
      },
      "pushkey4": {
        "full_object": "goes here"
      }
    }
  },
  "alarms": {
    "pushkey1": {
      "reduced_object": "mainly_the_time"
    },
    "pushkey4": {
      "reduced_object": "mainly_the_time"
    }
  }
}

The user_alarms node contains each user alarm, that way the user can see all the alarms that have set. The node alarms is the denormalization for the original node and is the node to be queried on each cron job. It contains a simpler object, only what is needed to perform the query for the upcoming alarms, mainly the trigger time. To improve performance after the FCM push is sent the corresponding object should be deleted.

Original Thread

By anonymous    2018-03-26

You could use a Cloud Function to generate you excel report, for example by using excel4node (https://www.npmjs.com/package/excel4node)

And to call this Cloud Function regularly, you have to trigger it via http through a cron-job.

Have a look at:

https://firebase.google.com/docs/functions/http-events).

and

https://www.youtube.com/watch?v=CbE2PzvAMxA

Note: What works quite well too is to generate some PDFs via the Cloud Function, using pdfmake.

Original Thread

By anonymous    2018-05-01

You will find hereafter links to tutorials or code examples covering your needs :

1/To call a Cloud Function regularly, you have to trigger it via http through a cron-job.

https://firebase.google.com/docs/functions/http-events).

and

https://www.youtube.com/watch?v=CbE2PzvAMxA

2/ For sending a notification:

https://firebase.google.com/docs/functions/use-cases#notify_users_when_something_interesting_happens

https://github.com/firebase/functions-samples/blob/master/developer-motivator/functions/index.js

https://android.jlelse.eu/serverless-notifications-with-cloud-functions-for-firebase-685d7c327cd4

PS: an extra advice : you should better store your dates as one String if possible. The best option being to convert your date to the number of milliseconds since January 1, 1970, 00:00:00 GMT

Original Thread

By anonymous    2018-05-21

You could do it with Cloud Functions, which "run backend code in response to events triggered by Firebase features and HTTPS requests", see the general doc here.

You could regularly trigger an HTTPS Cloud Functions that would:

  1. Call the REST API, e.g. with Request (https://github.com/request/request)
  2. Based on the response of the REST API, send a notification with FCM.

To send a FCM notification via Cloud Function, have a look a this official Firebase sample https://github.com/firebase/functions-samples/tree/master/fcm-notifications

To call your HTTPS Cloud Function regurlarly, you have to trigger it via http through a cron-job.

Have a look at: https://firebase.google.com/docs/functions/http-events and https://www.youtube.com/watch?v=CbE2PzvAMxA. You could also use another online CRON service to call the HTTPS Function, like https://www.easycron.com/

Note that you would need to be on Blaze Plan to be able to query an outside service.

Original Thread

Popular Videos 20

Submit Your Video

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