How to send FCM push notification dynamically?

Viewed 586

As firebase FCM will send the push notification to the Android/IOS device immediatly. Is it possible to schedule the push notification based how user sets event reminder time like in Google Calendar reminder ?

For example, User A sets an event A to remind before 10 minutes. User B sets an event B to remind before 1 minutes.

One solution that I have is to run Cron Job every minutes and trigger the push notification but I don't think this is efficient if there are more users. Is there any way to schedule push notification in Firebase?

2 Answers

You can use the schedule functions in firebase cloud messaging to schedule your FCM push notification

Refer : https://firebase.google.com/docs/functions/schedule-functions?hl=en

you can use the schedule function:

functions.pubsub.schedule().onRun()

which will add the topic in cloudscheduler and you can define how often this has to run.

but the catch is, the firebase allows you to use this only on pay as you go plan (Blaze plan)

In my case, i did the below:

  1. Managed the queuing by inserting the device_token and when to send in a mysql db table
  2. Wrote a daemon which looks for the mysql entries and run the FCM Push notification call on the desired duration.

You can create a function that triggers FCM notifications and then use Google Cloud Tasks to trigger that function with the relevant payload. To break it in simple steps:

1. Add a Cloud Task when a user sets an event:

exports.addEvent = functions.https.onCall((data, context) => {
  // add data in database
  // add a Google Cloud Task
  return

  // Alternatively, you can add the event directly to database
  // and then use Firebase/Realtime DB triggers for Cloud Functions
});

You can pass the duration in which the Cloud Tasks should trigger. If your event is in 10 hours then just pass 36000 seconds as the parameter. After 10 hours, the Cloud task will trigger your function that sends FCM notifications.

2. Handle the reminder and send notifications:

exports.sendNotifications = functions.https.onRequest((req, res) => {
  // read payload from req.body
  // process and send FCM notification
});

You should add URL of your sendNotifications functions in the Google Cloud Task. You can read more about creating HTTP target tasks in the documentation.

To summarize the flow:

  1. User creates and event
  2. A cloud function then creates a Google Tasks with appropriate duration
  3. Cloud tasks trigger your sendNotifications function which then uses FCM to trigger noticiations.
Related