If you really want to it as background job on a Asp.Net WebApp you should look into:
Quartz.Net
Create a job to send e-mail
public class SendMailJob : IJob
{
public void Execute(IJobExecutionContext context)
{
...Do your stuff;
}
}
Then configure your job to execute daily
// define the job and tie it to our SendMailJob class
IJobDetail job = JobBuilder.Create<SendMailJob>()
.WithIdentity("job1", "group1")
.Build();
// Trigger the job to run now, and then repeat every 24 hours
ITrigger trigger = TriggerBuilder.Create()
.WithIdentity("trigger1", "group1")
.StartNow()
.WithSimpleSchedule(x => x
.WithIntervalInHours(24)
.RepeatForever())
.Build();
HangFire
RecurringJob.AddOrUpdate(
() => YourSendMailMethod("email@email.com"),
Cron.Daily);
IHostedService (only in Asp.Net Core)
public class SendMailHostedService : IHostedService, IDisposable
{
private readonly ILogger<SendMailHostedService> _logger;
private Timer _timer;
public SendMailHostedService(ILogger<SendMailHostedService> logger)
{
_logger = logger;
}
public Task StartAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("Hosted Service running.");
_timer = new Timer(DoWork, null, TimeSpan.Zero,
TimeSpan.FromSeconds(5));
return Task.CompletedTask;
}
private void DoWork(object state)
{
//...Your stuff here
_logger.LogInformation(
"Timed Hosted Service is working. Count: {Count}", executionCount);
}
public Task StopAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("Timed Hosted Service is stopping.");
_timer?.Change(Timeout.Infinite, 0);
return Task.CompletedTask;
}
public void Dispose()
{
_timer?.Dispose();
}
}
In your startup.cs class. add this at configure method.
services.AddHostedService<SendMailHostedService>();
If do not need to host it as a backgroud job on your WebApp, then you can create a Windows Service that runs every day on the time you need.
See this question: Windows service scheduling to run daily once a day at 6:00 AM