BotSharp/src/Infrastructure/BotSharp.Core.Crontab/Services/CrontabEventSubscription.cs

65 lines
2.2 KiB
C#
Raw Normal View History

2025-01-24 21:50:28 +00:00
using BotSharp.Abstraction.Infrastructures.Events;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace BotSharp.Core.Crontab.Services;
public class CrontabEventSubscription : BackgroundService
{
private readonly ILogger _logger;
private readonly IServiceProvider _services;
public CrontabEventSubscription(IServiceProvider services, ILogger<CrontabEventSubscription> logger)
{
_logger = logger;
_services = services;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("Crontab event subscription background service is running.");
using (var scope = _services.CreateScope())
{
2025-01-28 23:00:08 +00:00
var publisher = scope.ServiceProvider.GetRequiredService<IEventPublisher>();
2025-01-24 21:50:28 +00:00
var subscriber = scope.ServiceProvider.GetRequiredService<IEventSubscriber>();
var cron = scope.ServiceProvider.GetRequiredService<ICrontabService>();
var crons = await cron.GetCrontable();
foreach (var item in crons)
{
_ = Task.Run(async () =>
{
2025-01-28 23:00:08 +00:00
// Clean unhandled messages
await publisher.RemoveAsync($"Crontab:{item.Title}", count: 100);
2025-01-24 21:50:28 +00:00
await subscriber.SubscribeAsync($"Crontab:{item.Title}",
"Crontab",
port: 0,
2025-01-28 23:00:08 +00:00
priorityEnabled: false,
async (sender, args) =>
2025-01-24 21:50:28 +00:00
{
var scope = _services.CreateScope();
cron = scope.ServiceProvider.GetRequiredService<ICrontabService>();
await cron.ScheduledTimeArrived(item);
2025-01-28 23:00:08 +00:00
},
stoppingToken: stoppingToken);
2025-01-24 21:50:28 +00:00
});
}
}
/*using (var scope = _services.CreateScope())
{
var cron = scope.ServiceProvider.GetRequiredService<ICrontabService>();
var crons = await cron.GetCrontable();
while (!stoppingToken.IsCancellationRequested)
{
await Task.Delay(1000, stoppingToken);
}
}*/
}
}