首页 > 解决方案 > 如何在固定日期前 24 小时在节点 js 中发送自动电子邮件?

问题描述

我想在我的节点应用程序中实现一个设置,服务器可以在特定日期前 24 小时向许多人发送电子邮件。该日期来自 DB。

例如:日期是 12 月 25 日,所以我需要我的服务器在 12 月 24 日向一组客户发送邮件。我今天如何对其进行编码,以便将来发送邮件?

(我的节点应用程序托管在 VPS 上,因此它将始终运行。)

标签: node.jsemailschedule

解决方案


您可以使用节点调度模块。https://www.npmjs.com/package/node-schedule

var schedule = require('node-schedule');
var date = new Date(2020, 12, 24, 5, 30, 0);

var j = schedule.scheduleJob(date, function(y){ });

或者你可以用老式的方式来做。就像是。

const then = "2020-12-24 05:00:00";

const inter = setInterval(() => {
    const now = new Date();
    if (Date.parse(now) > Date.parse(then)) {
       clearInterval(inter);
    }
}, 1000 * 60 * 60 );

编辑:

你可以有类似的东西。

const schedules = {};

function dbUpdate() {
    const somedate = new Date();
    const userid = getUpdatedUser();
    cancelSchedule(userid);
    createSchedule(userid, somedate);
}

function createSchedule(userid, somedate) {
    const date = new Date(somedate);
    schedules[userid] = schedule.scheduleJob(date, function(y){ });
}

function cancelSchedule(userid) {
    schedules[userid].cancel();
}

未经测试,但沿着这些路线


推荐阅读