-
Notifications
You must be signed in to change notification settings - Fork 2
Services
Services are singletons that extend upon the entire lifetime of the application.
Services can also be hosted, by running AddHostedService(), and thus you can run code on the application starting/stopping. These are used to login/out of Dexter when the user closes, aswell as flush the AuditLog(ger), etc. Quite often, these services extend Event
.
Typically, services are classes that are used by others, or do a specific function to that module. This differentiates itself from items in the Events folder, which are specifically for announcers, audit loggers, and the handler for that module, which specifically contain the module's events, or the direct communication of those events.
For instance, if a service needs to run once on the startup of the application, but after the bot has logged in, you can hook into the BotEventHandler _eventHandler.OnGuildRegistered method.
For example, a service might look like this:
namespace MASZ.Bot.Services;
public class ScheduledCacher : Event
{
private const int CacheIntervalMinutes = 15;
private readonly BotEventHandler _eventHandler;
public ScheduledCacher(BotEventHandler eventHandler)
{
_eventHandler = eventHandler;
}
public void RegisterEvents()
{
_eventHandler.OnBotLaunched += StartCaching;
}
public async Task StartCaching()
{
Timer eventTimer = new(TimeSpan.FromMinutes(CacheIntervalMinutes).TotalMilliseconds)
{
AutoReset = true,
Enabled = true
};
eventTimer.Elapsed += async (_, _) => await LoopThroughCaches();
await Task.Run(() => eventTimer.Start());
}
public async Task LoopThroughCaches()
{
...
}
}