Reputation: 1229
I think this is one of the hardest problems im dealing with in my app, i have installed moment.js (using mrt). and what i want to do is let the user pick a date and a time that the server will send an email to that user friends. so for example: now is thursday 9:13 pm and the user want to send the message monday at 6:47 am. and after the user have set the time i want the email to be sent repeatedly every week at the day and time that the user have set. so i thought using moment.js like that (client side):
var now = moment(); (the current date and time).
then use a datepicker like jqueryui or a common one, and a timepicker,for setting the time and date that the user selected like that(client side):
var day = user selection using datepicker;
var time = user selection using timepicker;
var result = moment.set(day,time);
insert the result to the database:
DateToSendEmail.insert({date:result});
and finally have the code to really execute the Email.send function (on the server side):
var DateToSend = DateToSendEmail.findOne({});
var thisMoment = moment();
if(DateToSend === thisMoment){
Email.send({
to:[friends]
from:"[email protected]"
Subject:"auto email send"
html:"auto email send"
});
}
the one thing that i don't know is whether it will work if the user isnt entering the the app for along time (lets say a month) or should i use Meteor.setInterval to execute this function repeatedly?
Upvotes: 0
Views: 487
Reputation: 64312
We do something very similar in our app:
Emails
collection with an emailAt
date.setInterval
on the server to regularly poll for emails to send.Your polling code may look something like:
Meteor.startup(function() {
if (process.env.METEOR_ENV === 'production') {
Meteor.setInterval(sendPendingEmails, ONE_HOUR);
}
});
Fortunately, Date
objects are written in UTC so any math you do on them should be independent of the timezone of either your users or your server. Furthermore, you can use $lte
when fetching from the Emails
collection like so:
var sendPendingEmails = function() {
var currentDate = new Date();
var pendingEmails = Emails.find({emailAt: {$lte: currentDate}}).fetch();
...
};
It's important to remember that your server could be reset/hang/etc. so you'd want to set a polling interval small enough to compensate for this and to get close to the emailAt
time without imposing too much load on your DB.
BTW if you run into any issues manipulating or comparing with moment objects you may want to call toDate()
on them before they interact with the DB.
Upvotes: 3