4

My database structure is something like this:

"users": {
"PXZwwGvu0lNwJeov8CMMrETnzVx1": {
      "name": "Ada Lovelace",
      "timestamp" : July 4, 2018 at 4:31:27 PM UTC+5:45
      "happy": true,
    }

"PXZwwGvu0lNwJeov8CMMrETnzVx2": {
      "name": "Charles Babbage",
      "timestamp" : July 5, 2018 at 5:29:15 PM UTC+5:45
      "happy": true,
    }
"PXZwwGvu0lNwJeov8CMMrETnzVx3": {
      "name": "Elon Musk",
      "timestamp" : July 7, 2018 at 9:21:37 PM UTC+5:45
      "happy": true,
    }
}

Here the "timestamp" denotes the time of creation of the document.I want to change the value of field "happy" from true to false exactly one day after the creation of document.The user may close the app after the document creation but the field value should still be changed. Is there any way to do so?

bimsina
  • 414
  • 5
  • 12

2 Answers2

4

I'd probably set up a Cloud Function for this. This is a piece of code that runs on Google's infrastructure and can interact with Firebase (and other cloud) resources.

If you schedule a Cloud Function to run every hour, you can run a database query that finds all users with a timestamp between 23 and 24 hours ago, and update those.

In pseudo-code this would look something like this:

var now = Date.now();
var 24hoursago = now - ...;
var 23hoursago = now - ...;
var ref = firebase.database().ref("users");
var query = ref.orderByChild("timestamp").startAt(24hoursago).end(23hoursago);
query.once("value").then(function(snapshot) {
  snapshot.forEach(function(user) {
    user.ref.update({ happy: false });
  });
});
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
1

You can use Firebase JobDispatcher; it uses JobScheduler to run tasks in the background, and you can set triggers for let's say 24 hours and then update your Firebase database child.

For example, a job can be triggered 24 hours after it's created with just this line.

.setTrigger(Trigger.executionWindow(60*60*24,60*60*24+60))

This library will also work when the device do not have Google play services installed and wants to schedule a job in the application. In this condition this library internally uses AlarmManager. If Google Play service is available on the device then it uses the scheduling engine inside Google Play services.

Tip: It uses AlarmManager to support API levels <= 21 if Google Play services is unavailable.

For devices running on API level 21, it uses JobScheduler.

Tip 2: If you need your job to be rescheduled, you can use this:

jobFinished(your_job,true);  // this line will reschedule your job after is finished
halfer
  • 19,824
  • 17
  • 99
  • 186
Gastón Saillén
  • 12,319
  • 5
  • 67
  • 77