Using Firebase Cloud Functions to fetch data from api? - firebase

I have a use case where I want to call an API to fetch data twice without any trigger from the front-end and I'm wondering if firebase cloud functions are of any help in this regard.
Basically what I. want is, to get data from API (twice a day), store it in firestore and firebase storage, and call the firebase API from the front-end.
Please suggest me, if I should even consider firebase cloud functions for the task!

You can use Firebase Scheduled Cloud Functions that runs twice a day:
exports.scheduledFunctionCrontab = functions.pubsub.schedule('0 0,12 * * *')
.timeZone('America/New_York') // Users can choose timezone - default is America/Los_Angeles
.onRun((context) => {
console.log('This will be run every day at 00:00 AM and 12:00 PM Eastern!');
// Do your stuff
//admin.firestore().collection("test").doc("test").set({...})
return null;
});
The above function will be triggered twice a day - once at midnight and second at 12 noon. There you can fetch your data from any 3rd party API and write it to firestore. The parameter passed in the schedule method is in cron syntax. You can experiment different cron schedules here

Related

Want to create a scheduled firestore script. Need pointers

Creating an App with Firestore. Need cloud function for document matches that creates new documents/records at periodic intervals.
Looked at firestore cloud functions but still not clear.
My existing knowledge: Create SQL Command bash script as a cron job.
I installed Firebase CLI, setup functions, created example but still unsure what documentation to read nor have good examples to manipulate firestore on a schedule.
Should I use realmDB instead?
App has chat component & data matching creates new records/documents every 6 hours.
Potentially creates upwards of 100,000 records/documents at a time - periodically purged after 14 days.
If you wish to use Firebase Cloud Functions to trigger at periodic intervals (similar to Cron jobs) and run some code, you can use this handy convenience method by Firebase Cloud Functions: https://firebase.google.com/docs/functions/schedule-functions.
exports.scheduledFunctionCrontab = functions.pubsub.schedule('5 11 * * *')
.timeZone('Asia/Kolkata')
.onRun((context) => {
console.log('This will be run every day at 11:00 AM IST!');
return null;
});
You can also setup Google Cloud Pub-Sub triggers manually and use Cloud Scheduler (a Cron job scheduler for GCP) to trigger Pub-Sub trigger.

Cloud Function for changing the value of a field inside a document after a time lapse? [duplicate]

I am looking for a way to schedule Cloud Functions for Firebase or in other words trigger them on a specific time.
Update 2019-04-18
There is now a very simple way to deploy scheduled code on Cloud Functions through Firebase.
You can either use a simple text syntax:
export scheduledFunctionPlainEnglish =
functions.pubsub.schedule('every 5 minutes').onRun((context) => {
console.log('This will be run every 5 minutes!');
})
Or the more flexible cron table format:
export scheduledFunctionCrontab =
functions.pubsub.schedule('5 11 * * *').onRun((context) => {
console.log('This will be run every day at 11:05 AM UTC!');
});
To learn more about this, see:
The Scheduling Cloud Functions for Firebase blog post introducing the feature.
The documentation on scheduled functions.
Note that your project needs to be on a Blaze plan for this to work, so I'm leaving the alternative options below for reference.
If you want to schedule a single invocation of a Cloud Function on a delay from within the execution of another trigger, you can use Cloud Tasks to set that up. Read this article for an extended example of how that can work.
Original answer below...
There is no built-in runat/cron type trigger yet.
For the moment, the best option is to use an external service to trigger a HTTP function periodically. See this sample in the functions-samples repo for more information. Or use the recently introduced Google Cloud Scheduler to trigger Cloud Functions through PubSub or HTTPS:
I also highly recommend reading this post on the Firebase blog: How to Schedule (Cron) Jobs with Cloud Functions for Firebase and this video: Timing Cloud Functions for Firebase using an HTTP Trigger and Cron.
That last link uses cron-job.org to trigger Cloud Functions, and works for projects that are on a free plan. Note that this allows anyone to call your function without authorization, so you may want to include some abuse protection mechanism in the code itself.
What you can do, is spin up an AppEngine instance that is triggered by cron job and emits to PubSub. I wrote a blog post specifically on that, you might want to take a look:
https://mhaligowski.github.io/blog/2017/05/25/scheduled-cloud-function-execution.html
It is important to first note that the default timezone your functions will execute on is America/Los_Angeles according to the documentation. You may find a list of timezones here if you'd like to trigger your function(s) on a different timezone.
NB!!: Here's a useful website to assist with cron table formats (I found it pretty useful)
Here's how you'd go about it:
(Assuming you'd like to use Africa/Johannesburg as your timezone)
export const executeFunction = functions.pubsub.schedule("10 23 * * *")
.timeZone('Africa/Johannesburg').onRun(() => {
console.log("successfully executed at 23:10 Johannesburg Time!!");
});
Otherwise if you'd rather stick to the default:
export const executeFunction = functions.pubsub.schedule("10 23 * * *")
.onRun(() => {
console.log("successfully executed at 23:10 Los Angeles Time!!");
});

Firebase Cloud Function schedule on Spark plan [duplicate]

I am looking for a way to schedule Cloud Functions for Firebase or in other words trigger them on a specific time.
Update 2019-04-18
There is now a very simple way to deploy scheduled code on Cloud Functions through Firebase.
You can either use a simple text syntax:
export scheduledFunctionPlainEnglish =
functions.pubsub.schedule('every 5 minutes').onRun((context) => {
console.log('This will be run every 5 minutes!');
})
Or the more flexible cron table format:
export scheduledFunctionCrontab =
functions.pubsub.schedule('5 11 * * *').onRun((context) => {
console.log('This will be run every day at 11:05 AM UTC!');
});
To learn more about this, see:
The Scheduling Cloud Functions for Firebase blog post introducing the feature.
The documentation on scheduled functions.
Note that your project needs to be on a Blaze plan for this to work, so I'm leaving the alternative options below for reference.
If you want to schedule a single invocation of a Cloud Function on a delay from within the execution of another trigger, you can use Cloud Tasks to set that up. Read this article for an extended example of how that can work.
Original answer below...
There is no built-in runat/cron type trigger yet.
For the moment, the best option is to use an external service to trigger a HTTP function periodically. See this sample in the functions-samples repo for more information. Or use the recently introduced Google Cloud Scheduler to trigger Cloud Functions through PubSub or HTTPS:
I also highly recommend reading this post on the Firebase blog: How to Schedule (Cron) Jobs with Cloud Functions for Firebase and this video: Timing Cloud Functions for Firebase using an HTTP Trigger and Cron.
That last link uses cron-job.org to trigger Cloud Functions, and works for projects that are on a free plan. Note that this allows anyone to call your function without authorization, so you may want to include some abuse protection mechanism in the code itself.
What you can do, is spin up an AppEngine instance that is triggered by cron job and emits to PubSub. I wrote a blog post specifically on that, you might want to take a look:
https://mhaligowski.github.io/blog/2017/05/25/scheduled-cloud-function-execution.html
It is important to first note that the default timezone your functions will execute on is America/Los_Angeles according to the documentation. You may find a list of timezones here if you'd like to trigger your function(s) on a different timezone.
NB!!: Here's a useful website to assist with cron table formats (I found it pretty useful)
Here's how you'd go about it:
(Assuming you'd like to use Africa/Johannesburg as your timezone)
export const executeFunction = functions.pubsub.schedule("10 23 * * *")
.timeZone('Africa/Johannesburg').onRun(() => {
console.log("successfully executed at 23:10 Johannesburg Time!!");
});
Otherwise if you'd rather stick to the default:
export const executeFunction = functions.pubsub.schedule("10 23 * * *")
.onRun(() => {
console.log("successfully executed at 23:10 Los Angeles Time!!");
});

Run a cron job only once after a set time

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.

Firebase how to schedule hourly operation [duplicate]

I am looking for a way to schedule Cloud Functions for Firebase or in other words trigger them on a specific time.
Update 2019-04-18
There is now a very simple way to deploy scheduled code on Cloud Functions through Firebase.
You can either use a simple text syntax:
export scheduledFunctionPlainEnglish =
functions.pubsub.schedule('every 5 minutes').onRun((context) => {
console.log('This will be run every 5 minutes!');
})
Or the more flexible cron table format:
export scheduledFunctionCrontab =
functions.pubsub.schedule('5 11 * * *').onRun((context) => {
console.log('This will be run every day at 11:05 AM UTC!');
});
To learn more about this, see:
The Scheduling Cloud Functions for Firebase blog post introducing the feature.
The documentation on scheduled functions.
Note that your project needs to be on a Blaze plan for this to work, so I'm leaving the alternative options below for reference.
If you want to schedule a single invocation of a Cloud Function on a delay from within the execution of another trigger, you can use Cloud Tasks to set that up. Read this article for an extended example of how that can work.
Original answer below...
There is no built-in runat/cron type trigger yet.
For the moment, the best option is to use an external service to trigger a HTTP function periodically. See this sample in the functions-samples repo for more information. Or use the recently introduced Google Cloud Scheduler to trigger Cloud Functions through PubSub or HTTPS:
I also highly recommend reading this post on the Firebase blog: How to Schedule (Cron) Jobs with Cloud Functions for Firebase and this video: Timing Cloud Functions for Firebase using an HTTP Trigger and Cron.
That last link uses cron-job.org to trigger Cloud Functions, and works for projects that are on a free plan. Note that this allows anyone to call your function without authorization, so you may want to include some abuse protection mechanism in the code itself.
What you can do, is spin up an AppEngine instance that is triggered by cron job and emits to PubSub. I wrote a blog post specifically on that, you might want to take a look:
https://mhaligowski.github.io/blog/2017/05/25/scheduled-cloud-function-execution.html
It is important to first note that the default timezone your functions will execute on is America/Los_Angeles according to the documentation. You may find a list of timezones here if you'd like to trigger your function(s) on a different timezone.
NB!!: Here's a useful website to assist with cron table formats (I found it pretty useful)
Here's how you'd go about it:
(Assuming you'd like to use Africa/Johannesburg as your timezone)
export const executeFunction = functions.pubsub.schedule("10 23 * * *")
.timeZone('Africa/Johannesburg').onRun(() => {
console.log("successfully executed at 23:10 Johannesburg Time!!");
});
Otherwise if you'd rather stick to the default:
export const executeFunction = functions.pubsub.schedule("10 23 * * *")
.onRun(() => {
console.log("successfully executed at 23:10 Los Angeles Time!!");
});

Resources