Egg.js 发送验证码后手动执行定时任务更新验证码状态
本文介绍如何在 Egg.js 中实现发送验证码方法,并在发送成功后手动执行一次定时任务,30分钟后根据邮件地址更新数据库中验证码状态为 0。
以下是在 Egg.js 中实现发送验证码方法,并手动执行一次定时任务的示例代码:
const Subscription = require('egg').Subscription;
class UpdateCodeStatus extends Subscription {
// 定义定时任务的配置
static get schedule() {
return {
cron: '0 */30 * * * *', // 每30分钟执行一次
type: 'worker', // 在一个 worker 上执行
immediate: true, // 立即执行一次
};
}
// 定义定时任务的具体执行逻辑
async subscribe() {
const { ctx } = this;
const { email } = ctx.args[0]; // 获取传入的email参数
// 根据email找到对应的记录,并更新验证码状态为0
const result = await ctx.model.User.update({ codeStatus: 0 }, { where: { email } });
console.log(`Updated ${result[0]} record(s) for email ${email}`);
}
}
class UserController extends Controller {
async sendCode() {
const { ctx } = this;
const { email } = ctx.request.body;
// 生成验证码并发送邮件
const code = Math.floor(Math.random() * 900000) + 100000;
await ctx.service.email.sendCode(email, code);
// 更新数据库中验证码的状态为1
const result = await ctx.model.User.update({ codeStatus: 1 }, { where: { email } });
console.log(`Updated ${result[0]} record(s) for email ${email}`);
// 手动执行一次定时任务,30分钟后更新验证码状态为0
await ctx.app.runSchedule('update_code_status', { email });
ctx.body = { code };
}
}
在上述代码中,我们定义了一个名为 UpdateCodeStatus 的定时任务,它会在每30分钟执行一次,并接受一个 email 参数。在定时任务的 subscribe() 方法中,我们根据传入的 email 参数,找到对应的记录,并将其验证码状态更新为 0。
在 UserController 中的 sendCode() 方法中,我们通过调用 ctx.service.email.sendCode() 方法向用户发送验证码,并在数据库中更新验证码状态为 1。接着,我们手动执行一次定时任务,传入该方法接受的 email 参数,以便在 30分钟后更新验证码状态为 0。
注意,在 UserController 中,我们需要在类的顶部引入 UpdateCodeStatus 类和 Subscription 类。另外,我们还需要在 config/config.default.js 文件中配置定时任务:
exports.schedule = {
enable: true,
package: 'egg-schedule',
};
以上就是在 Egg.js 中实现发送验证码方法,并手动执行一次定时任务的示例代码。
原文地址: https://www.cveoy.top/t/topic/nppX 著作权归作者所有。请勿转载和采集!