I am trying to call an api every minute for ski lift status and check for changes. I am going to store the value of if the lift is open or closed in firebase (Real Time Database) and read to see if value from api is different and only update/ write to that node when it's a different value. Then I can set up a cloud function that will listen for database changes and send push notifications to the list of FCM tokens from that channel. I am not sure if this is the most efficient way, but I was going to set up scheduled functions to call the third party api.
I have been using these docs:
https://firebase.google.com/docs/functions/schedule-functions
I was planning to do something like this:
exports.scheduledFunction = functions.pubsub.schedule('every 5 minutes').onRun((context) => {
CALL MY API IN HERE AND UPDATE DATABASE IF SNAPSHOT BACK IS DIFFERENT
});
I was wondering how would I run only between set times- say 8am-6pm EST. I am struggling to find anything about times to run. Should I just run the function every minute and then pause and resume by checking the time? In which case how does it know to keep checking the time when it is paused?
Firebase scheduled functions use Cloud Scheduler to implement the schedule. It accepts cron style time specifiers to indicate when a job should be run. The full spec for that can be found here. You will have to use ranges of numbers to indicate the valid times and frequency of the schedule. For example, you might use "8-18" in the hour field to limit the hours of execution.
Related
I need to actively receive crash notifications for firebase functions.
Is there any way to set up Slack webhooks to receive a message when Firebase Functions throw an Error, functions crash, or something like that?
I would love to receive issue messages by velocity ie: Firebase Functions crash 50 times a day.
Thank you so much.
First you have to create a log based (counter) metric that will be counting specific error occurencies and second - you create alerting policy with Slack notification channel.
Let's start from finding corresponding logs that appear when the function throws an error. Since I didn't have one that would crash I used logs that indicated that it was started.
Next you have to create a log based metric. Ignore the next screen and go to Monitoring > Alerting. Click on "Create new policy", find your metric and select "Rolling Window" to whatever time period you need. For testing I used 1 minute. Then set "Rollind windows function" to "mean".
Now configure when the alert has to be triggered - I chose over 3 (within 1 minute window).
On the next screen you select notification channel. In case of Slack it has to be configured first in "Notification Channels".
You can save policy the policy now.
After a few minutes I gathered enough data to generate two incidents:
And here's some alerting related documentation that may help you understand how to use them.
So in my android app, I am using the real-time database to store information about my users. That information should be updated every Monday at 00:00 o'clock. I am using a cloud function to do this but the problem here is the time zones. Right now I have set the time zone to 'Europe/Sofia' for testing purposes. In the documentation, it is said that the time zone for cloud functions must be from the TZ database. So I figured I could ask the user before registering in my app their preferred time zone and save it in the database. My question is after getting the user's prefered time zone is there a way to only write one cloud function and execute it dynamically for each time zone in the TZ database or do I have to create individual functions for each time zone in the TZ database?
If I correctly understand your question, you could have a scheduled Cloud Function which runs every hour from 00:00 to 23:00 UTC+14:00 on Mondays, and, for every execution (i.e. for every hour within this range), query for the users that should be updated and execute the updates.
I'm not able to enter more into details, based on the info you have provided.
It's not possible to schedule a Cloud Function using a dynamic timezone. You must know the timezone at the time you write the function and declare it statically in your code.
If you want to schedule something dynamically, read through your options in this other question: https://stackoverflow.com/a/42796988/807126
So, you could schedule a repeating function that runs every hour, and check to see if something should be run for a user at the moment in time that it was invoked. Or, you can schedule a single future invocation of a function with a service like Cloud Run, and keep rescheduling it if needed.
I need to run a cron job to perform a specific cloud function after a set interval only once but a bit unsure of how to do it. Is there any way to do this through the current google cloud platform?
Update following our discussion below through comments:
If you want to "change a document in your Firestore database 2 hours after it has been created" you could do as follows:
When creating the document in Firestore, save the date/time of creation, e.g. with firebase.firestore.FieldValue.serverTimestamp()
Have an HTTP Cloud Function that you call regularly as explained below (every minutes? every 5 minutes?) and that, first, selects the documents that were created 2 hours ago (based on the saved timestamp) and then do the desired action on these docs.
If you want to trigger a Cloud Function through a cron job, note that you would normally do that through an HTTP Cloud Function, calling the Cloud Function URL via the cron job.
You can either use an external service like cron-job.org or you can use GCP's App Engine and Cloud Pub/Sub
See this video: https://www.youtube.com/watch?v=fEBPAMSk5_8
and this Blog post: https://firebase.googleblog.com/2017/03/how-to-schedule-cron-jobs-with-cloud.html
both from the Firebase team.
Finally note that recently GCP launched a new product, Cloud Scheduler, which can be used to call HTTP Cloud Functions.
Sorry for late answer. Once upon time, I am stuck with this issue too. You sure can schedule a job executed once at particular time. But, you must use multiple platform as Firebase Cloud Function has time limit to cron task. If you look at Quotas and limits document for Time Limit of Firebase, you can see that Firebase cloud functions have set time limits until they are canceled (540 seconds or 9 minutes). So you can't cron a job executed after more than 9 minute with cloud function. But you can use Heroku server to cron a job without paying. Unfortunately, Heroku apps sleep after 30 minutes if there is no task along the time interval. However, you can keep awake with external server such as cron-job.org. You can get unlimitedly your app awake by applying pinging to your Heroku app every minute less than 30 minutes. You can use node-schedule to cron a job executed once for all time by using this code there:
const schedule = require('node-schedule');
const date = new Date(2012, 11, 21, 5, 30, 0);
const job = schedule.scheduleJob(date, function(){
console.log('The world is going to end today.');
});
You can get current time or timestamp for Firestore and add time interval to current date to schedule as you desire. Dont forget to use timezone for it. You can use rule to set timezone like that:
const rule = new schedule.RecurrenceRule();
rule.dayOfWeek = [0, new schedule.Range(0, 6)]; //all days
rule.hour = req.body.hour;
rule.minute = req.body.minute;
rule.second = req.body.second;
rule.tz = "Europe/Istanbul"; // You can specify a timezone!
Here, you can get request from client side by fetching time specification from user. And use schedule job module for one time task like that:
const job = schedule.scheduleJob(rule, function(data) {
console.log("Job ran #", new Date().toString());
}.bind(null, dataFuture));
Here you can use user data with .bind() by entering variable just like dataFuture variable. If your users use native android platform, you can specify time interval by entering hour_of_day and minute as:
Date currentTime = Calendar.getInstance().getTime();
Locale aLocale = Locale.forLanguageTag("tr-TR");
Calendar calendar = Calendar.getInstance(aLocale);
calendar.setTime(currentTime);
calendar.add(Calendar.MINUTE, 1);
calendar.add(Calendar.HOUR_OF_DAY, 4);
Alternatively you can use Cloud Task platform. But it may be a bit hard to use.
I am making a spam counter ( on Firebase ). What I do is I use database trigger on firebase cloud functions to increment a path (/counter/${uid}). This path will hold an integer for each user that other path will have a security rule that reference to it and check whether it exceed the limit. However, I would like to clear the counter once a day.
When I search on google I found official way of firebase to do this by using another Google cloud service to deploy cron job. However, I wonder if I use setInterval on cloud function instead would work. This task would only be a one line execution ( admin.database().ref('/counter').set({}) . And it is not so serious that if it were to skip once or twice of the execution due to some problem, it should be ok.
Thanks
The use of setInterval won't work, and it's not really ever recommended to do so. You can use setInterval to keep a function alive for some amount of time, but you will be paying for that time even if the function is just waiting. Also you are still subject to the way Cloud Functions will time out your function (default 60 seconds, max 9 minutes by special configuration).
Don't use setInterval as you'll be paying for un-used compute time.
Instead see this video on YouTube; https://www.youtube.com/watch?v=CbE2PzvAMxA
They go into detail of how to setup a free-schedule service and setup a HTTP trigger that should achieve the result you're after.
Is it possible on Firebase or Parse to set up something kinda like a cron job?
Is there a way to set up some sort of timed operation that runs over the stored user data?
For example, I'm writing a program that allows people to RSVP for lunch everyday. If you have RSVPed by noon, then you get paired up with somebody else who has also RSVPed. Using JavaScript, the user can submit their RSVP in the browser.
The question is, can Firebase/Parse execute the code to match everyone at 12:00pm every day?
Yes, this can be done with Parse. You'll need to write your matching function as a background job in cloud code, and then you'll need to schedule the task in the dashboard. In terms of the flexibility in scheduling, it's not as flexible as cron but you can definitely run a task at the same time every day, or every x minutes/hours.
Tasks can take 15 mins max to execute before they're killed, so depending on the size of your database or the complexity of your task, you may need to break it up into different tasks or make it resumable.
Just to confirm about Firebase:
As #rickerbh said, it can be done with Parse, but currently there is no way for you to run your code on Firebase's server. There are 2 options for you 2 solve this:
You could use Firebase Queue and run your code in Node.js
You could use a different library such as Microsoft Azure (I still haven't tried this yet, I'm not sure if it provides Job Scheduling for Android)
However, Firebase is working on something called Firebase Trigger, which will solve our problem, however it is still not released with no confirmed release date.