🚧 Core API and abstractions extending

This commit is contained in:
2020-03-02 00:00:44 +04:00
parent ed255e2506
commit e86049f4fd
7 changed files with 198 additions and 0 deletions
@@ -0,0 +1,76 @@
using System;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using BotFramework;
using Microsoft.Extensions.Logging;
using Telegram.Bot.Exceptions;
using Telegram.Bot.Types;
namespace Kruzya.TelegramBot.Core.Service
{
public abstract class AbstractTimedHostedService
{
private Timer _timer;
protected readonly ILogger _logger;
protected readonly ITelegramBot _bot;
protected virtual TimeSpan TimerPeriod => TimeSpan.FromSeconds(45);
protected AbstractTimedHostedService(ILogger logger, ITelegramBot bot)
{
_bot = bot;
_logger = logger;
}
#region IHostedService
public Task StartAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("Message sender service is starting.");
_timer = new Timer(Run, null, TimeSpan.Zero, TimeSpan.FromSeconds(1));
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("Message sender service is stopping.");
_timer?.Change(Timeout.Infinite, 0);
return Task.CompletedTask;
}
#endregion
#region IDisposable
/// <summary>
/// Disposes the timer.
/// </summary>
public void Dispose()
{
_timer?.Dispose();
}
#endregion
private async void Run(object state)
{
_timer?.Change(Timeout.Infinite, 0);
try
{
await OnRun();
}
finally
{
var timerPeriod = this.TimerPeriod;
_timer?.Change(timerPeriod, timerPeriod);
}
}
protected virtual async Task OnRun()
{
await Task.Delay(500);
}
}
}