Scheduled messages without setInterval()

感情迁移 提交于 2019-12-11 15:57:01

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!