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?
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();
}
}
}
}
Marius VasilePosted Oct 11, 2022, 6:49 PM
After many trials it worked with
BackgroundService as scoped service with cron timing
Jayant TripathyPosted Oct 10, 2022, 5:09 PM
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 VasilePosted Oct 10, 2022, 4:56 PM
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 TripathyPosted Oct 10, 2022, 4:43 PM
Please check this link https://jayanttripathy.com/create-windows-service-background-jobs-in-net-core/
You can set your timing like below,
Rajanikant HawaldarPosted Oct 10, 2022, 4:28 PM
https://www.c-sharpcorner.com/blogs/scheduling-in-asp-net-mvc-core