Node.js 中使用定时任务传递参数:将 email 值传递给 verifyCodeUpdate.js

在 Node.js 中,使用定时任务时,有时需要将一些信息传递给定时任务执行的脚本文件。例如,在使用邮箱验证码功能时,需要将用户的 email 地址传递给 verifyCodeUpdate.js 文件,以用于验证代码的有效性。

以下代码展示了如何在 Node.js 中将 email 值传递给 verifyCodeUpdate.js 文件:

async SaveCode(email, code) {
    const { ctx, app } = this
    const hasCode = await app.mysql.get('email_code', { email })
    const row = {
        email,
        code
    }
    const option = {
        where: {
            email
        }
    }
    if (!hasCode) {
        const createCode = await app.mysql.insert('email_code', row)
    }
    else {
        const updateCode = await app.mysql.update('email_code', row, option)
    }
    console.log('即将执行定时任务')
    ctx.app.runSchedule('verifyCodeUpdate', email); // 将 email 值作为参数传递进去
}

//verifyCodeUpdate.js
module.exports = {
    schedule: {
        interval: '1m', // 1 分钟间隔
        type: 'all', // 指定所有的 worker 都需要执行
    },
    async task(ctx, email) { // 在这里接收 email 参数
        console.log('定时任务执行了', ctx, email)
    },
};

说明:

  • 在 SaveCode 函数中,我们将 email 作为参数传递给 ctx.app.runSchedule('verifyCodeUpdate', email),用于启动定时任务并传递 email 值。
  • 在 verifyCodeUpdate.js 文件中,我们在 task 函数中添加了一个参数 email,用于接收从 SaveCode 函数传递过来的 email 值。

通过这种方法,我们就可以将 email 值传递给 verifyCodeUpdate.js 文件,以便在定时任务执行时使用。

注意:

  • 确保 verifyCodeUpdate.js 文件中的 task 函数能够正确接收和处理 email 参数。
  • 使用定时任务时,需要根据实际情况设置合理的执行间隔和类型。
Node.js 中使用定时任务传递参数:将 email 值传递给 verifyCodeUpdate.js

原文地址: https://www.cveoy.top/t/topic/npq9 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录