Small fix for a reminder query

This commit is contained in:
Kwoth
2022-03-24 01:51:49 +01:00
parent c3fda25a93
commit 75f0574cc8

View File

@@ -1,12 +1,13 @@
#nullable disable #nullable disable
using LinqToDB; using LinqToDB;
using LinqToDB.EntityFrameworkCore; using LinqToDB.EntityFrameworkCore;
using NadekoBot.Common.ModuleBehaviors;
using NadekoBot.Services.Database.Models; using NadekoBot.Services.Database.Models;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
namespace NadekoBot.Modules.Utility.Services; namespace NadekoBot.Modules.Utility.Services;
public class RemindService : INService public class RemindService : INService, IReadyExecutor
{ {
private readonly Regex _regex = private readonly Regex _regex =
new( new(
@@ -28,20 +29,25 @@ public class RemindService : INService
_db = db; _db = db;
_creds = creds; _creds = creds;
_eb = eb; _eb = eb;
_ = StartReminderLoop();
} }
private async Task StartReminderLoop() public async Task OnReadyAsync()
{ {
while (true) using var timer = new PeriodicTimer(TimeSpan.FromSeconds(15));
while (await timer.WaitForNextTickAsync())
{
await OnReminderLoopTickInternalAsync();
}
}
private async Task OnReminderLoopTickInternalAsync()
{ {
await Task.Delay(15000);
try try
{ {
var now = DateTime.UtcNow; var now = DateTime.UtcNow;
var reminders = await GetRemindersBeforeAsync(now); var reminders = await GetRemindersBeforeAsync(now);
if (reminders.Count == 0) if (reminders.Count == 0)
continue; return;
Log.Information("Executing {ReminderCount} reminders", reminders.Count); Log.Information("Executing {ReminderCount} reminders", reminders.Count);
@@ -59,7 +65,6 @@ public class RemindService : INService
Log.Warning(ex, "Error in reminder loop: {ErrorMessage}", ex.Message); Log.Warning(ex, "Error in reminder loop: {ErrorMessage}", ex.Message);
} }
} }
}
private async Task RemoveReminders(IEnumerable<int> reminders) private async Task RemoveReminders(IEnumerable<int> reminders)
{ {
@@ -71,10 +76,10 @@ public class RemindService : INService
await uow.SaveChangesAsync(); await uow.SaveChangesAsync();
} }
private Task<List<Reminder>> GetRemindersBeforeAsync(DateTime now) private async Task<List<Reminder>> GetRemindersBeforeAsync(DateTime now)
{ {
using var uow = _db.GetDbContext(); await using var uow = _db.GetDbContext();
return uow.Reminders return await uow.Reminders
.ToLinqToDBTable() .ToLinqToDBTable()
.Where(x => x.ServerId / 4194304 % (ulong)_creds.TotalShards == (ulong)_client.ShardId .Where(x => x.ServerId / 4194304 % (ulong)_creds.TotalShards == (ulong)_client.ShardId
&& x.When < now) && x.When < now)