问题
I want to schedule some things like sending messages with my discord bot.
E.g.: I want the bot to send "Good Morning" every day at 8 am or announce some things.
My problem is: I can't use something like setInterval() to execute every 24 hours because if the bot goes offline or has to be restarted it would reset or delay the interval.
Question: How do I execute something at a specific point in time without having to worry about the bot sometimes being offline?
回答1:
You can use the cron package: you schedule a job that runs every day at a specific hour (time will be read on the system clock, you'll have to figure it out by yourself for timezones).
Here's an example of a message being sent every day at 8:00 am.
const cron = require('cron');
const channel; // Let's say this is the channel where you want to send it.
const job = new cron.CronJob('0 0 8 * * *', () => {
channel.send("It's 8:00 am.");
});
About the 0 0 8 * * * pattern: its format is second minute hour month-day month week-day.
You can find more about cron patterns here.
来源:https://stackoverflow.com/questions/56027698/scheduled-messages-without-setinterval