isaacs / node-lru-cache

A fast cache that automatically deletes the least recently used items
http://isaacs.github.io/node-lru-cache/
ISC License
5.38k stars 353 forks source link

Clear or reset the cache regularly #190

Closed XzyZachary closed 2 years ago

XzyZachary commented 2 years ago

Excuse me. How to clear the cache regularly?For example, every morning at 10:00

isaacs commented 2 years ago

You can call cache.clear() any time you like.

To do it every morning at 10:00 is a bit weird, but I guess you could do something like this in your application:

const resetAt10AM = cache => {
  const now = new Date()
  let t = new Date(now.toISOString().split('T') + 'T10:00Z')
  if (t < Date.now()) t = new Date(t + 24 * 60 * 60 * 1000)
  setTimeout(() => {
    setInterval(() => cache.clear(), 24*60*60*1000)
  }, Date.now() - t)
}

resetAt10AM(myLRUCache)

Or you could have a cron or something that hits your server with a signal to tell it to reset.

// server.js
process.on('SIGUSR1', () => myLRUCache.clear())
fs.writeFileSync('server.pid', String(process.pid))
# reset-cache.sh
kill -SIGUSR1 $(cat server.pid)

Then add a crontab like this:

0 10 * * * bash reset-cache.sh
XzyZachary commented 2 years ago

You can call cache.clear() any time you like.

To do it every morning at 10:00 is a bit weird, but I guess you could do something like this in your application:

const resetAt10AM = cache => {
  const now = new Date()
  let t = new Date(now.toISOString().split('T') + 'T10:00Z')
  if (t < Date.now()) t = new Date(t + 24 * 60 * 60 * 1000)
  setTimeout(() => {
    setInterval(() => cache.clear(), 24*60*60*1000)
  }, Date.now() - t)
}

resetAt10AM(myLRUCache)

Or you could have a cron or something that hits your server with a signal to tell it to reset.

// server.js
process.on('SIGUSR1', () => myLRUCache.clear())
fs.writeFileSync('server.pid', String(process.pid))
# reset-cache.sh
kill -SIGUSR1 $(cat server.pid)

Then add a crontab like this:

0 10 * * * bash reset-cache.sh

Thanks,I have the same idea. I used node-schedule in my nuxt app later.