I have a background task to send emails that work but it works continously. I want to make it fire at a spoecific time of day. How do I do that?
C#
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
var dataAzi = DateTime.Now;
var data = await _context.MemoratClassDetails.Include(s => s.MemoratClassSubCategory)
.ThenInclude(s => s.MemoratClassCategory)
.Where(s => s.MemDataReminder.Year == dataAzi.Year && s.MemDataReminder.Month == dataAzi.Month && s.MemDataReminder.Day == dataAzi.Day && s.Reminder == false)
.ToListAsync();
while (!stoppingToken.IsCancellationRequested)
{
if (data.Count() > 0)
{
foreach (var i in data)
{
var category = i.MemoratClassSubCategory.MemoratClassCategory.MemCategory;
var uemail = "[email protected]";
var subcategory = i.MemoratClassSubCategory.MemSubCategory;
var message = i.MemData;
var emailCom = new MimeMessage();
emailCom.From.Add(new MailboxAddress(_smtpSettings.SenderName, _smtpSettings.SenderEmail));
emailCom.To.Add(new MailboxAddress(uemail));
emailCom.Cc.Add(new MailboxAddress("[email protected]"));
emailCom.Subject = "Reminder!";
var bodybuilder = new BodyBuilder();
bodybuilder.HtmlBody = @"
Contact Notification
Categorie: " + category + @"
Subcategorie: " + subcategory + @"
Detaliu: " + message + @"
This is a message received because you set a reminder on rosafety.com
";
emailCom.Body = bodybuilder.ToMessageBody();
using (var client = new SmtpClient())
{
await client.ConnectAsync(_smtpSettings.Server, _smtpSettings.Port, true);
client.AuthenticationMechanisms.Remove("XOAUTH2");
await client.AuthenticateAsync(_smtpSettings.UserName, _smtpSettings.Password);
await client.SendAsync(emailCom);
await client.DisconnectAsync(true);
}
var mdid = i.MemoratDetID;
var editData = await _context.MemoratClassDetails.FindAsync(mdid);
editData.Reminder = true;
await _context.SaveChangesAsync();
}
}
}
}

Rajanikant HawaldarRank #110 · 20.2K reputationPosted Oct 10, 2022, 12:28 PM EDT
https://www.c-sharpcorner.com/blogs/scheduling-in-asp-net-mvc-core
Jayant TripathyRank #1,432 · 1.1K reputationPosted Oct 10, 2022, 12:43 PM EDT
Please check this link https://jayanttripathy.com/create-windows-service-background-jobs-in-net-core/
You can set your timing like below,
Marius VasileRank #785 · 2.9K reputationPosted Oct 10, 2022, 12:56 PM EDT
Thank you Jayant and Rajanikant. I tried to stay away from other libraries like Quartz and Hangfire. The above code is working fine sending email the problem I have is that is sending continuously and is reclying my pool when published.
I am looking for a simpler solution to add a timer
Jayant TripathyRank #1,432 · 1.1K reputationPosted Oct 10, 2022, 1:09 PM EDT
Marius, You can check this link where it used threading/timer control
https://www.coreprogramm.com/2019/08/how-to-create-windows-service-in-net.html
https://www.coreprogramm.com/2019/08/windows-service-csharp.html
Marius VasileRank #785 · 2.9K reputationPosted Oct 11, 2022, 2:49 PM EDT
After many trials it worked with
public sealed class BackgroundWork : BackgroundService { private readonly IServiceProvider _serviceProvider; public BackgroundWork(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { // Schedule the job every day. await WaitForNextSchedule("0 0 * * *"); using var scope = _serviceProvider.CreateScope(); var scopedSchedulerService = scope.ServiceProvider.GetRequiredService(); await scopedSchedulerService.ExecuteAsync(stoppingToken); } } private async Task WaitForNextSchedule(string cronExpression) { var parsedExp = CronExpression.Parse(cronExpression); var currentUtcTime = DateTimeOffset.UtcNow.UtcDateTime; var occurenceTime = parsedExp.GetNextOccurrence(currentUtcTime); var delay = occurenceTime.GetValueOrDefault()-currentUtcTime; await Task.Delay(delay); } }BackgroundService as scoped service with cron timing