0

I have an application in which a user can manage multiple alarms (set a new alarm, edit it, or snooze)

When the alarm time is reached I need to notify the user. If a user clicks snooze, the time_end field gets 5 minutes added to it.

How can I track when the alarm times have been reached?

I have tried using a collection.observe() - but it only works once, on server start

Server: Meteor Startup

var expiredAlarms = Alarms.find({$and: [{"time_end": {$lt: moment()._d}}, {notification_sent: false}]});

expiredAlarms.observe({
    added: function(doc) {
        console.log('alarm timeout has been reached');
        processAlarmEnd(); //set notification_sent to true
    },
    removed: function(doc) {
        console.log('A notification has been sent');
    }
});

The above code only works when the app is started and processes all notifications for expired alarms - but once new alarms expire, nothing happens. My guess is because moment()._d does not change and the same old query is called over and over again.

Should I place this code in a Tracker.autorun - will that help? Any suggestions on doing this better/smarter?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Habib
  • 279
  • 1
  • 2
  • 9

1 Answers1

1

To make code execute in the future, you need to use setTimeout. In your observe query, don't care about the time, and in the added callback, calculate how many milliseconds remains till the alarm should go off, and use setTimeout to call processAlarmEnd after that amount of milliseconds.

You may also need to cancel a setTimeout with clearTimeout in the removed callback.

Peppe L-G
  • 7,351
  • 2
  • 25
  • 50
  • Yes that's a great idea...but how do I manage a large collection of setTimeout functions? – Habib Feb 04 '15 at 10:49
  • I guess this would work [How do you handle multiple instances of setTimeout()?](http://stackoverflow.com/questions/315078/how-do-you-handle-multiple-instances-of-settimeout) – Habib Feb 04 '15 at 11:00
  • @Habib, yea, storing all the handles calls to `setTimeout` returns in an object in a variable outside the `added` and `removed` callbacks seems like a good idea. But make sure you delete the handles from the object when the alarms are over (so the object don' contains old handles that won't be used any more). – Peppe L-G Feb 04 '15 at 12:57