I will go with a redis based solution that sets ttl with bull that picks yp the task when time elapsed and sends the emails to the recipients.
const express = require('express');
const bodyParser = require('body-parser');
const { Queue, Worker } = require('bull');
const nodemailer = require('nodemailer');
const app = express();
const port = 3000;
// In-memory storage for reminders (replace this with a database in production)
const remindersQueue = new Queue('reminders', { redis: { port: 6379, host: 'localhost' } });
app.use(bodyParser.json());
// Endpoint for creating reminders
app.post('/create-reminder', async (req, res) => {
const { email, datetime, message } = req.body;
const job = await remindersQueue.add({ email, message }, { delay: new Date(datetime) - new Date() });
res.status(200).json({ success: true, message: 'Reminder created successfully', jobId: job.id });
});
// Set up a worker to process reminders
new Worker('reminders', async job => {
const { email, message } = job.data;
// Send email
await sendEmail(email, 'Reminder', `Reminder: ${message}`);
});
// Function to send email using nodemailer (replace with your email service details)
async function sendEmail(to, subject, text) {
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: '[email protected]',
pass: 'your-email-password',
},
});
const mailOptions = {
from: '[email protected]',
to,
subject,
text,
};
return transporter.sendMail(mailOptions);
}
// Start the server
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
})
;