How to run cron job with Firebase?
Asked Answered
C

7

29

I am trying to run a cron job with Firebase. Basically I need to run a function that makes a ton of API calls and pushes data to firebase at 12:00am PST every day. Is there a way for me to do this on the server side with Firebase?

I see that there's this module here, but I don't understand how it works at all. If anyone has any ideas or know how the aforementioned module could work that would be fantastic.

EDIT: Idea. What if I were to create a data entry that showed the time that the function was completed. Basically check to see that last time the function was called and completed. If it's past 12am then the function is called and the field is updated so it's not called until the next day. Would this be a good idea? I don't need the function to happen at 12am exactly, I just need it to be completed by the time the first user logs in.

Calves answered 2/3, 2016 at 3:2 Comment(11)
Firebase only stores data - to run a cron job you'll need to have access to your own server.Orva
@Orva I just edited the question...do you think that will be an okay solution?Calves
You'll still need to have something to check the data entry - most likely your own serverOrva
@Orva couldn't I just check the entry on the front-end during user login?Calves
Hmm actually that would work, you'll just have to ensure that it's run before the user logs in I guessOrva
@Orva awesome thanks! I'll give it a go and see how it worksCalves
That looks like a huge hack. I wouldn't like to log in to a server that uses my login to trigger a "Ton of API calls" that need to complete before I manage to login. Do not recommend it.Riffraff
@Riffraff when I said user login I really meant first user to access the site. Still a bad idea?Calves
Well it still looks like a hack to me. But it all depends you said " I just need it to be completed by the time the first user logs in" so if when the user accesses the site and the TON of API calls begin, is something preventing him to log in? Will there be any impact on the client? If so, I recommend building a little web server and using it to run this and future jobs.Riffraff
@Riffraff Cheers thanks. I'm going to build a backend to do this now.Calves
@ElliottMcNary, just posted an answer. Could you please check out if it would work for you?Shelbashelbi
V
33

At I/O 2019 it was announced a new feature to do cronjobs with firebase functions.

Check it out

Snippet 1

export scheduledFunction = functions.pubsub.schedule(‘every 5 minutes’).onRun((context) => {
  console.log(‘This will be run every 5 minutes!’);
});

Snippet 2

exports.scheduleJobs = functions.pubsub.
schedule(“every day 03:00”).onRun(async() => {
 // do something
console.log(“All done! See you tomorrow morning!”);
});
Vyse answered 9/5, 2019 at 16:18 Comment(1)
finally no need to deploy separately to gcloud!Bluegrass
S
5

There are no cron job or schedule options on Firebase, you have to use another platform for that. Here´s one, for example: https://zapier.com/zapbook/firebase/schedule/

More information: Best way to globally set up alerts for when a Firebase location is changed

There are also some online cron jobs you can use, just search for "online cron job" with Google. Basically, they just call an URL in the specified time.

Update: There are cron jobs now, see https://mcmap.net/q/482735/-how-to-run-cron-job-with-firebase

Shimkus answered 10/6, 2016 at 19:54 Comment(0)
J
5

Last month Firebase released the Cloud Functions.

There, you can trigger lambda-like functions depending on different hooks: Pub/Sub events, HTTP events, ... They are planning to release a cron hook where you can trigger a specific function using a cron rule. It's not released yet, but meanwhile you can use Google App Engine

Jello answered 6/4, 2017 at 20:50 Comment(3)
firebase.googleblog.com/2017/03/…Hildagarde
Shame it's only available on Blaze pricing plan though... Not so sure about switching to uncapped billing while I'm still learning.Octopus
@ego therefor you can create a budget on google cloud. If you set the budget to 0$ you surely don't have to pay anything.Kazoo
N
2

To answer the question about how firebase-cron works:

This module needs to be run on a server someplace so it's always on. When jobs are run, all this means is that it takes the specified data for that job and puts it into the specified firebase-queue reference. As a user, you set up the firebase-queue to run when the data is added to the queue.

You can add a "cron" job by specifying the name, the cron pattern, and the data add to the queue using the .addJob method:

cron.addJob('foo', '0 0 0 * * *', {foo: 'bar'}, function(err) {
  if (err) return console.error(err);
  console.log('added foo');
});

Use the .run method to start firebase-cron. This checks the list of jobs and executes any that needed to be executed. This method also takes a callback function that will be called each time the jobs are checked (I use this for additional logging)

There are some things that I want to add to firebase-cron and it's documentation but haven't gotten to them yet. I've been using it in production environments for a while now and haven't had any problems with firebase-cron itself... just user errors in my queue logic ;)

Also, I've been using the new Firebase Cloud Functions and they're great. I may add a feature to be able to trigger a cloud function instead of using firebase-queue. This probably won't be necessary once their cron service is running.

Nadene answered 11/5, 2017 at 16:19 Comment(0)
S
2

Solution 1

Back in March 2017 Abe Haskins published an article on how to utilize Google's App Engine Cron to schedule cron jobs for Firebase. If you want to follow this approach, you will need:

  • git
  • Python 2.7
  • Python pip
  • Google Cloud SDK

Solution 2

There's a cool tutorial by Jeff Delaney on how to make dynamic cron jobs for Firebase. You can have a look at it here.

The goal of this solution is to provide dynamic task scheduling that can be managed both clientside and serverside based on user interaction. Let’s consider some uses cases:

  • Scheduled or snooze-able reminder notifications
  • Send a happy birthday push notification
  • Send welcome email 24 hours after signup
  • Retry tasks if they fail due to errors

Solution 3

Finally, you can also use free third-party cron job services like cron-job.org. It looks pretty straight-forward and it gives you:

  • Execution up to 60x an hour
  • Status notifications
  • Execution history

Hope that some of these will help.

Shelbashelbi answered 21/1, 2019 at 11:56 Comment(0)
C
0

If you don't want to use a free online HTTP trigger/request generator (e.g. https://atrigger.com/), one approach is to fire the cloud function upon user (client-side) interaction with your app. A stored number type field could hold a UNIX timestamp. If that timestamp is greater than 24 hours old, continue to fire your server-side cloud function (and refresh timestamp) else stop/break/quit. Could be a week or month or whatever time interval you want.

What if no user interacts with your app? In that case, why update your app's data? Regarding stale data for the 1st user, that's a matter of tuning your time interval. Also, you could possible alert the user that new data is being fetched and to hold on/wait.

Chad answered 14/3, 2019 at 2:43 Comment(0)
S
0

CREATE SCHEDULE CLOUD FUNCTIONS (NODE.JS):

---> UPDATED 21/05/2024 <----

I think that you can create a Scheduled firebase cloud function for that.

This may help you implement it:

    // SCHEDULED FUNCTION THAT RUNS EVERY DAY AT 12:00 PDT
    myScheduledFunction: functions
        .pubsub.schedule("every day 12:00")
        .onRun((context) => {
            // ...
        }),

"Context" parameter here is not very useful, at least to me, but for clarity I've also added the official docs for it so you can know what it is as well.

You can also edit the schedules with Cloud Scheduler tool, at GCP console!!!

RELATED DOCUMENTATION LINKS

"Cloud Scheduler" tool:

https://console.cloud.google.com/cloudscheduler

Cron Syntax docs:

https://cloud.google.com/scheduler/docs/configuring/cron-job-schedules

Cron jobs official documentation:

https://cloud.google.com/appengine/docs/legacy/standard/python/config/cronref

Context parameter:

https://firebase.google.com/docs/reference/functions/firebase-functions.eventcontext.md#eventcontext_interface

Cron calculator: https://crontab.guru/

PS: This is my first real answer from Stack Overflow, so fell free to improve it. But the answer is right and solid. I would WISH that someone had said this here before I've tried to search it all and find out about Cloud Scheduler tool..

Strawworm answered 17/5 at 17:25 Comment(1)
You can also change PDT to PST and vise versa with Cloud Scheduler tool..Strawworm

© 2022 - 2024 — McMap. All rights reserved.