Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
    }
}
like image 604
hesham shawky Avatar asked Oct 19 '25 09:10

hesham shawky


1 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.

like image 121
Ishara Sandun Avatar answered Oct 20 '25 22:10

Ishara Sandun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!