I have to send report via email everyday at a particular time. In order to do that I used BackgroundService in Asp.Net Core MVC for preparing a report to be sent later via email. The thing is that it sends two emails in same time even though i created it in a singleton pattern and it with 1 min delay. I didn't encounter any problem when I debugged it with Visual Studio and it sent only once on localhost instead of azure. As I mentioned above when it was run on Azure it sent the email twice. While i prepare report i give its name like yyyyMMdd_HH_mm_ss so two emails name are Report_20201223_22_00_36 and Report_20201223_22_00_46. So I feel like there are two thread instead of one thread. The code what i wrote is below.
//SendReportWorker.cs public class SendReportWorker : BackgroundService { private readonly SendReportWorkerSettings SendReportWorkerSettings; private readonly ILogger<SendReportWorker> logger; public SendReportWorker(ILogger<SendReportWorker> logger, SendReportWorkerSettings SendReportWorkerSettings) { this.SendReportWorkerSettings = SendReportWorkerSettings; this.logger = logger; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { try { var now = DateTimeOffset.UtcNow; //SendReportWorkerSettings.ExecuteHourMinuteUtc = ["12:00"] if (Array.Exists(SendReportWorkerSettings.ExecuteHourMinuteUtc, q => q == now.ToString("HH':'mm"))) { logger.LogInformation("SendReportWorker running at: {time}", DateTimeOffset.Now); // Preparing Report ... // Sending Report Via Email ... } } catch (Exception ex) { logger?.LogError(ex.ToString()); } await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken); } } } ///Startup.cs public void ConfigureServices(IServiceCollection services) { services.AddHostedService<SendReportWorker>(); }
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)