Add adds an item to the cache, with the specified callback to be called when the item is removed from the cache upon timeout. If the item is removed from the cache using a call to Remove before the timeout expires, the callback will not be called. If the Add was successful, it returns (newly added
(key, item any, callback func())
| 58 | // an existing entry for the specified key, the cache entry is not be updated |
| 59 | // with the specified item and it returns (existing item, false). |
| 60 | func (c *TimeoutCache) Add(key, item any, callback func()) (any, bool) { |
| 61 | c.mu.Lock() |
| 62 | defer c.mu.Unlock() |
| 63 | if e, ok := c.cache[key]; ok { |
| 64 | return e.item, false |
| 65 | } |
| 66 | |
| 67 | entry := &cacheEntry{ |
| 68 | item: item, |
| 69 | callback: callback, |
| 70 | } |
| 71 | entry.timer = time.AfterFunc(c.timeout, func() { |
| 72 | c.mu.Lock() |
| 73 | if entry.deleted { |
| 74 | c.mu.Unlock() |
| 75 | // Abort the delete since this has been taken care of in Remove(). |
| 76 | return |
| 77 | } |
| 78 | delete(c.cache, key) |
| 79 | c.mu.Unlock() |
| 80 | entry.callback() |
| 81 | }) |
| 82 | c.cache[key] = entry |
| 83 | return item, true |
| 84 | } |
| 85 | |
| 86 | // Remove the item with the key from the cache. |
| 87 | // |