1

I'm writing a Discord bot and having it schedule a cron job when it starts up using node-cron. I've defined it as follows (very basic so far):

    cron.schedule('15 1,3,5,7,9,11,13,15,17,19,21,23 * * *', () => {
        GameUpdater.sendGameUpdatesToLeagueChannels(this.guilds);
    });

The problem is, Discord bots will often reconnect which will rerun the portion of the code where this has to be. I'm considering having a check of an external value, perhaps in my database, that manages whether or not it's run recently or is already running or something like that, but I was wondering if there was a proper way to make a cron job unique using node-cron?

muttley91
  • 12,278
  • 33
  • 106
  • 160

3 Answers3

2

First, you need somewhere to save the name of the scheduled task, which defaults to a UUID V4 but can be provided as an option using the 3rd argument of the schedule method you are calling above.

With a reference to this name, either from a database or a constant that is hard-coded in the script you have wrote, you can use cron.getTasks to list all of the scheduled tasks to ensure that the current task doesn't already exist before scheduling it.

If you are referencing a hard-coded name, then calling the schedule method will replace the existing scheduled task, rather than creating a new task.

UPDATE

To set the name of the scheduled task, simply pass in an options object as a third argument to the schedule method you are calling, with a name for your task.

Example:

cron.schedule('15 1,3,5,7,9,11,13,15,17,19,21,23 * * *', () => {
    GameUpdater.sendGameUpdatesToLeagueChannels(this.guilds);
}, { name: "example-task-1234" });
Alex Ander
  • 1,430
  • 12
  • 19
  • Do you have any example of passing a hard-coded name? I haven't been able to find anything on this, the docs don't seem to suggest that a third parameter would be a name for the job. I'd be happy to hard-code the names though if just calling schedule for that same name would replace the existing job, it'd solve my problem. – muttley91 Feb 13 '22 at 06:55
  • Updated my answer with an example for what you want. – Alex Ander Feb 14 '22 at 14:01
  • There isn't actually anything in the documentation that says you can set a name for your scheduled task. – Alex Ander Feb 14 '22 at 14:02
0

if the cron schedule is fired on startup from Client.on('ready') have your cronjob to be scheduled at a separate event Client.once('ready'), this way it won't fire the routine again when the bot reconnects. Only if the entire shard/cluster process is terminated and restarted.

Lucas Flicky
  • 126
  • 1
  • 1
  • 9
0

You can you use logger to keep track of restaring or starting time of your server. You can use winston Click HERE

It will help to generate your server log so that you can read it before starting of your server, so that you can take your action. Like say adjust the time etc

Tanjin Alam
  • 1,728
  • 13
  • 15