diff --git a/src/Notifications/HeartbeatHostedService.cs b/src/Notifications/HeartbeatHostedService.cs new file mode 100644 index 000000000..c90394aa7 --- /dev/null +++ b/src/Notifications/HeartbeatHostedService.cs @@ -0,0 +1,62 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using Bit.Core; +using Microsoft.AspNetCore.SignalR; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; + +namespace Bit.Notifications +{ + public class HeartbeatHostedService : IHostedService, IDisposable + { + private readonly ILogger _logger; + private readonly IHubContext _hubContext; + private readonly GlobalSettings _globalSettings; + + private Task _executingTask; + private CancellationTokenSource _cts; + + public HeartbeatHostedService( + ILogger logger, + IHubContext hubContext, + GlobalSettings globalSettings) + { + _logger = logger; + _hubContext = hubContext; + _globalSettings = globalSettings; + } + + public Task StartAsync(CancellationToken cancellationToken) + { + _cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + _executingTask = ExecuteAsync(_cts.Token); + return _executingTask.IsCompleted ? _executingTask : Task.CompletedTask; + } + + public async Task StopAsync(CancellationToken cancellationToken) + { + if(_executingTask == null) + { + return; + } + _logger.LogWarning("Stopping service."); + _cts.Cancel(); + await Task.WhenAny(_executingTask, Task.Delay(-1, cancellationToken)); + cancellationToken.ThrowIfCancellationRequested(); + } + + public void Dispose() + { } + + private async Task ExecuteAsync(CancellationToken cancellationToken) + { + while(!cancellationToken.IsCancellationRequested) + { + await _hubContext.Clients.All.SendAsync("Heartbeat"); + await Task.Delay(120000); + } + _logger.LogWarning("Done with heartbeat."); + } + } +} diff --git a/src/Notifications/Startup.cs b/src/Notifications/Startup.cs index 0543fb068..c8f2c10e0 100644 --- a/src/Notifications/Startup.cs +++ b/src/Notifications/Startup.cs @@ -68,6 +68,7 @@ namespace Bit.Notifications // Mvc services.AddMvc(); + services.AddHostedService(); if(!globalSettings.SelfHosted) { // Hosted Services