SetTimeout in express callback

I am creating a route where a data attribute called "active" is being set to true, but after an hour is set to false. I am wondering if it is possible or bad practice to call a settimeout function in the express callback. Such as;

app.get("/test", (req, res) => {

//Some code

SetTimeout(func, 3600);
});

Is this bad for scalling, if this route was hit many times would it be very expensive? Thanks in advance.

Answers:

Answer

If you store those values in a database, then you should not create a timer per entry in node that will reset this value. Especially it if it is a lang lasting timer, Session like/related data that should last longer then a few seconds should in general not be keept in the memory of the node process.

The more frequently your site is visited, the more likely it is that you have at least one timer running at any time. As soon as this is the case you are not able to restart the application without either loosing that timer. Or you need to wait until all timers are finished and while that don't accept any new ones.

And you cannot switch to clustered mode, because then if one user calls that route twice, it might end up in two different processes, each of those processes would not know of the timeouts the other process has set.

So a better idea is to add a timestamp into the database, and one cleanup timer responsible for all entries.

Answer

It seems you only need to set 1 timer. This assumes the 'hour' starts at the first request.

let timer = null
let data = true

app.get("/test", (req, res) => {

  //Some code
  if (!timer) {
    timer = setTimeout(() => {data=false}, 3600);
  }
});

Instead, for multiple users, you can avoid setting multiple timers by putting a timestamp in a hash and polling it per request or a separate interval timer.

// init
let timers = {}

// in request
if (!timers[user]) {
    timers[user] = new Date().getTime() / 1000 + 3600
}
else if (timers[user] <= new Date().getTime() / 1000)
{
    // update db, etc
}


// or poll for expirations in separate single timer routine
let now = new Date().getTime() / 1000
Object.keys(timers).forEach(user => {
  if (timers[user] <= now) {
    // update db, etc
  }
})

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.