If you are in need of a solution to execute code at a specific time, such as setting up scheduled jobs, look no further than the scheduler library known as node-schedule. This library can be seamlessly integrated into your firebase cloud function
to efficiently manage and automate tasks. While it does add a level of dependency, its functionality proves to be quite beneficial in streamlining processes. In order to maintain a stateless firebase function, the alternate option outlined below must be considered. Take a closer look at the practical example provided using this library and a cloud function.
1. Utilizing node-schedule
const functions = require('firebase-functions');
var schedule = require('node-schedule');
exports.scheduleSampleJob = functions.https.onRequest((req , res) => {
/*
For instance, if you want a specific function to run at 5:30am on December
21, 2012. Remember - when working with JavaScript - 0 represents January and 11 represents December.
*/
var date = new Date(2012, 11, 21, 5, 30, 0);
var j = schedule.scheduleJob(date, function(){
console.log('The Task has been executed');
});
return res.status(200).send(`Task has been successfully scheduled`);
});
Note: Ensure that this function is only called once to avoid multiple job creations.
2. Implementing Firebase Function Pub/Sub
While Firebase provides support for job scheduling through Pub/Sub, it is reserved for those on the Blaze plan, and transcends the limitations of the Free or Flame plans. The usage of Pub/Sub
is detailed in the official Docs.
To schedule functions to run at specified times, utilize functions.pubsub.schedule().onRun()
. This convenient method establishes a Google Cloud Pub/Sub topic, employing Google's Cloud Scheduler to initiate events on said topic, ensuring precise execution schedules.
exports.scheduledFunctionCrontab = functions.pubsub.schedule('5 11 * * *')
.timeZone('America/New_York') // Users can select timezone - default is America/Los_Angeles
.onRun((context) => {
console.log('This will run daily at 11:05 AM Eastern!');
return null;
});
3. Exploring OneSignal Push Notification
To simplify manual scheduling, consider utilizing OneSignal as an alternative option. Offering comprehensive push notification services for a variety of platforms including Web, IOS, Android, and more, OneSignal integrates seamlessly with firebase cloud messaging. Additionally, it supports REST-api functionalities, allowing for easy scheduling of push notifications through built-in delivery features. Instead of developing a custom solution, exploring the capabilities of OneSignal could prove to be a valuable choice. By creating a firebase cloud function that directly interfaces with the OneSignal REST api, push notifications can be scheduled efficiently.