Regular time checks in nodejs?

Viewed 244

I have a discord bot with a mongodb database. He has a moderation commands, in this case a mute command. Each time a moderator mutes a member, the member receives a «muted» role and value of mute in the database equal to the current UNIX time + seconds of the mute time. Then, in the main file when I start the application, I create timers (setInterval ()), which once a minute query the database and check if the current time is longer than the time in the database. If so, the participant is removed from the role of mute and the value is reset.

Question: Is this a good practice? How can you do better? (I do not consider the option of starting the setTimeout () timer after issuing a punishment, because in this case, when the application is restarted, the participant will never be unmuted)

Thank!

2 Answers

Possible Solutions:

  1. Use setTimeout() on every mute.

PRO:

  • Best timing. Every used gets unmuted at the perfect time with nearly zero delay.
  • Only uses the database if someone is muted.

CON:

  • If your app crashes all the timeouts are gone. You could fix this by adding a startup routine that unmutes all old mutes and adds new timeouts for every still muted users.
  • Also a lot of muted users could create a lot of timeouts and consume more ressources.
  1. Use setInterval()

PRO:

  • Reduces the database actions to 1 per interval.
  • Works even after a restart of the app.

CON:

  • Makes database checks even if noone get ever muted.
  • Users will have an delay to get unmuted.

Conclusion:

There is no rigth or wrong in your case. I would suggest taking the solution 2 because it's more scaleable.

I think setTimeout is the simplest way here. If you would want to make it restart safe you should add a call on startup that will check for all muted users in your mongoDb and call setTimeout with the timestamp that is saved in the mongo. This way you are sure nobody gets left muted.

In the case that the user is still in the DB but the time already expired you can also call the setImmediate or directly call the clearing functions.

Related