简体   繁体   中英

nodejs timers performance

I have to create a timed application in nodejs, the users can set daily,weekly and monthly. my first tought was to create something like this:

socket.on("connect")
{
  client.on("authenticate")
  {
    var frequency = GetTimersForUser(client);
    var timersInMilliseconds = ConvertFrequencyToMS(frequency);
    var nextInMS = GetLower(timersInMilliseconds);
    setTimeout("timedCount()",nextInMS );
  }
}
timedCount()
{
  cancelTimer;
  client.emit("poke");
  var frequency = GetTimersForUsers(client); 
 ...
  setTimeout("timedCount()",nextInMS );
}

but this wont alert me about failed timers ( if client is disconnected) because the timer is only created after connection, so i though about creating the timers, before the connection. So, is it faster to create 1 timer every second:

    userslist = getIndividualUsersNextTimerAsDate();
  setTimout("timedCount()",1000);
    timedCount()
    {
      foreach(user in userslist)
      {
       if(user.time <= now())
       {
        if(user.socket)
        {
        user.socket.emit("poke");
        }
        user.time = resetTimeForNextTimer(user);
       }
      }
    }
    socket.on("connect")
    {
      ...
      userslist[x].socket = client;
    } 

or multiple timers every "time":

var userslist = GetUsersTimers();
  foreach(user in userslist)
  {
    user.Counter = setTimeout("runTime()",client.timer );
  }
 runTime(client)
 {
  client.emit("poke");
  client.Counter.cancel();
  client.timer = resetToNextTimer();
  client.Counter = setTimeout("runTime()",client.timer );
 }

or is there any better way that i'm missing?

It sounds like some of your timers could last for days, but connections usually don't survive that long. Will the users re-connect to the server and always be connected?

Assuming that users are always connected, then I would store the end time in database. In case the server goes down you can recover the end time and restart gracefully. When you get a new timer, use setTimeout to go to sleep. On restart, you can re-do setTimeout since you know the end time and current time (ie get the duration).

This would work work a "reasonable" number of timers. If you're going to have millions of these timers, it might actually be better to use setInterval that wakes up every X milliseconds/seconds/minutes, checks if any of the end times have passed, acts on those, and goes back to sleep.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM