Click here to Skip to main content
15,357,967 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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.


What I have tried:

//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>();
 }
Posted
Updated 1-Apr-22 9:41am

1 solution

You have a "while" loop; and you send without breaking out.
   
Comments
amagitech 25-Dec-20 1:07am
   
In fact in loop i have await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken);
I don't want to stop it after sending mail. Because it has to send email again 12:00 in next days. It's daily job so it must repeat everyday.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900