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

Viewed 8602

I'm building a notifications trigger method and wanted to be run 3 times per day at specific times.

I have checked the documentation but didn't understand that regex code for and how to customize it as I need it!

Now my method looks like this: ( it now runs evey min at second 45th for testing ) I need it for example runs at 6pm, 8pm, 11pm every day

@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);
    }
}
3 Answers

If you need to run it at 6pm, 8pm and 11pm try something like this. (Use your timezone)

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"
 });

I have used node-cron here. https://www.npmjs.com/package/node-cron

Hope this helps.

Please change your cron to the given below:

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

Above given cron will run your function on every day at 6pm, 8pm and 11pm.

You can use site crontab.guru as a playground for crontab patterns. Also it provides understandable examples and tips.

As already mentioned in another answer pattern suitable for you would be 0 18,20,23 * * *, you can modify it and look how it changed here.

Related