NestJs 如何在特定时间每天 3 次 运行 一个 cron 作业

NestJs how to run a cron job 3 times a day at specific times

我正在构建通知触发方法,并希望在特定时间每天 运行 3 次。

我已经查看了文档,但不了解正则表达式代码以及如何根据需要自定义它!

现在我的方法是这样的:(它现在 运行s 每分钟 45 秒进行测试)我需要它,例如每天下午 6 点、晚上 8 点、晚上 11 点 运行s

@Cron('45 * * * * *')
async sendNotificaiotns() {
    console.log('sending notification');

    try {
        const randomArticle = await this.articleRepository
            .createQueryBuilder()
            // .select("id")
            // .getMany();
            // .select("id")
            .orderBy("RAND()")
            .limit(1)
            .getOne();

        const input = new NotificationBySegmentBuilder()
            .setIncludedSegments(['Active Users', 'Inactive Users'])
            .notification() // .email()
            .setAttachments({
                data: {
                    ...randomArticle,
                },
                big_picture: encodeURI(randomArticle.image)
            })
            .setHeadings({ 'en': randomArticle.title })
            .setContents({'en': randomArticle.excerpt })
            .build();

        console.log(randomArticle);
        await this.oneSignalService.createNotification(input);

    } catch (e) {
        console.log(e);
    }
}

如果您需要在下午 6 点、晚上 8 点和晚上 11 点运行,请尝试这样的操作。 (使用您的时区)

var cron = require('node-cron');

cron.schedule('0 18,20,23 * * *', () => {
   console.log('Runing a job at 6pm,8pm and 11pm at America/Sao_Paulo timezone');
 }, {
   scheduled: true,
   timezone: "America/Sao_Paulo"
 });

我这里用到了node-cron。 https://www.npmjs.com/package/node-cron

希望对您有所帮助。

您可以使用网站 crontab.guru as a playground for crontab patterns. Also it provides understandable examples and tips

另一个适合你的答案模式已经提到0 18,20,23 * * *,你可以修改它,看看它是如何改变的here

请将您的 cron 更改为以下内容:

@Cron('0 0 18,20,23 * * *')

以上给定的 cron 将在每天下午 6 点、晚上 8 点和晚上 11 点 运行 您的函数。