Firebase Cloud Function schedule on Spark plan [duplicate] - firebase

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!!");
});

Related

repeated firebase deploy functions pub/sub creates duplicate scheduler jobs

I use the following command to deploy my project, one of the functions being a pub/sub:
firebase deploy --only functions
...and everything happens just fine, but the scheduler job is created a 2nd time, an exact copy of the previous one every time I deploy again.
I don't change the pub/sub function, so I would not necessarily need to include it during deploy, but why is it creating a new scheduler job every time? Neither the function, nor the topic in Pub/Sub is duplicating, only the scheduler job - why?
Here is how the pubsub function looks like, if relevant:
export const scheduledStuff = functions.pubsub
.schedule('0 0 * * *')
.timeZone('America/New_York')
.onRun(() => {
// do stuff
})
Update Jun 17 2022: I didn't specifically mention this, but the code I gave above, I hoped, should have given it away: I'm using the ES6 annotation for the function, ie. use import instead of require for packages, and the function is exported as export const scheduledStuff... instead of exports.scheduledStuff....
My functions are then separated into 2 categories, functions:functions, which are all the functions that are NOT pubsub, and this one pubsub. This is because I wanted to prevent the deployment of the pubsub function to my staging environment, so I'm using firebase deploy --only functions:functions for that one.
For this purpose I have an index file in my main functions directory that looks something like this:
import { default as firstFunction } from './callables/firstFunction.js'
import { default as secondFunction } from './callables/secondFunction.js'
//...
export const functions = {
firstFunction,
secondFunction,
//...
}
import { scheduledStuff } from './pubsub/scheduledStuff.js'
export const pubSubStuff = { scheduledStuff }
I tried to reproduce your case by deploying the below scheduler function which will run every minute and create a pubsub topic and a scheduler job.
In my case, my first deploy firebase deploy –only functions created a pubsub topic firebase-schedule-scheduledFunctionCrontab-us-central1 and a scheduler job firebase-schedule-scheduledFunctionCrontab-us-central.
With the second deployment firebase deploy –only functions, neither a duplicate scheduler job was created nor a duplicate pubsub topic.
My terminal shows the below lines:
functions: updating Node.js 16 function scheduledFunctionCrontab(us-central1)...
✔ functions[scheduledFunctionCrontab(us-central1)] Successful update operation.
The last deployment run got updated but a duplicate is not created. Also the scheduler function keeps updating the last run time and next run time field which confirms that the function is running every minute.
If what you have shared here, is the entire code of your scheduler function, then I think this is a Customer issue/bug.
Still to confirm I would like to have a look at your logs, but if you are confident that this is not an intended behavior (which seems to be according to me) please raise a support ticket with Google Cloud Support or raise a Customer issue in a public issue tracker

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!!");
});

Manually trigger scheduled or trigger function

Is there any way to manually trigger a scheduled function and/or a Firestore trigger function? I have two scenarios I need to solve:
A cloud function that is listening to a Firestore document (onCreate) didn't fire - it failed on 3 of about 1,000 invocations, so I need to manually trigger it for these 3 documents. Is this possible (to manually trigger this function)?
I have a scheduled function that runs hourly, but threw an error b/c of a map in the Firestore document when the code expected an array. Any way I can manually run the scheduled function once rather than waiting an hour before it runs again?
-- firebase console
-- functions
-- "..." at right side of cron job
-- "view in cloud scheduler"
-- "run now" at right side of function
You can run a firestore scheduled function via the FirebaseTools and running it locally. Starting the shell command eg npm run build && firebase functions:shell will allow you to invoke a Scheduled Function eg:
export const parseGarminHealthAPIActivityQueue = functions.region('europe-west2').runWith({
timeoutSeconds: TIMEOUT_IN_SECONDS,
memory: MEMORY
}).pubsub.schedule('every 10 minutes').onRun(async (context) => {
await parseQueueItems(ServiceNames.GarminHealthAPI);
});
It's not possible to manually trigger a function from the Firebase console. Your best bet is to use the methods shown in the Cloud documentation, which involve using gcloud's call command or the Cloud console's Testing tab. Neither of these are very easy, as you will have to construct the JSON payload to the function manually.
If I may make a suggestion - if your functions are failing due to errors, you should consider enabling retry on your functions, and making sure that your functions only generate errors for situations that should be retried. Depending on manual invocation in the event of a failure will not scale very well - errors should be handled by code as much as possible.

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