慶軍之菜鳥記錄-定期檢查並刪除資料

forhells發表於2024-03-20

不得不說,跟大佬們的差距是億點點啊。

 1 private async Task ExpiryScanLoop()
 2 {
 3     var cancelToken = _scanExpiryCancellationToken!.Token;
 4     while (cancelToken.IsCancellationRequested == false)
 5     {
 6         try
 7         {
 8             await Task.Delay(_options.ExpiryKeyScanInterval, cancelToken);
 9             using var sessionWrap = GetSessionWrap();
10             using var iter = sessionWrap.Session.Iterate();
11             while (iter.GetNext(out _) && cancelToken.IsCancellationRequested == false)
12             {
13                 var key = iter.GetKey();
14                 var context = new StoreContext<ValueWrapper<TValue>>();
15                 var result = sessionWrap.Session.Read(key, context);
16                 if (result.status.IsPending)
17                 {
18                     sessionWrap.Session.CompletePending(true);
19                     context.FinalizeRead(out result.status, out result.output);
20                 }
21 
22                 if (result.status.Found && result.output.HasExpired(_systemClock.NowUnixTimestamp()))
23                 {
24                     sessionWrap.Session.Delete(key);
25                 }
26             }
27         }
28         catch (Exception ex)
29         {
30             _logger?.LogWarning("Exception thrown in expiry scan loop:{Ex}", ex);
31         }
32     }
33 }

這段程式碼摘抄於時總的FasterKv.Cache.Core.

如果是我,我只會timer然後1s一次的去執行。

補充初始化與結束

...init

private readonly CancellationTokenSource? _scanExpiryCancellationToken;
    public TimeSpan ExpiryKeyScanInterval { get; set; } = TimeSpan.FromMinutes(5);
 private void Dispose(bool _)
 {
     _scanExpiryCancellationToken?.Cancel();...

相關文章