Created
April 16, 2022 02:14
-
-
Save brianmed/0765f8105f9bf5530e5df484962dfa32 to your computer and use it in GitHub Desktop.
Example BackgroundService with C# ASP.Net Core
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.EntityFrameworkCore; | |
namespace Joy.HostedServices; | |
public class EmailQueueHostedService : BackgroundService | |
{ | |
private IServiceScopeFactory ScopeFactory { get; init; } | |
public EmailQueueHostedService(IServiceScopeFactory scopeFactory) | |
{ | |
ScopeFactory = scopeFactory; | |
} | |
protected override async Task ExecuteAsync(CancellationToken stoppingToken) | |
{ | |
using PeriodicTimer periodicTimer = new(TimeSpan.FromSeconds(30)); | |
try | |
{ | |
while (await periodicTimer.WaitForNextTickAsync(stoppingToken)) | |
{ | |
using IServiceScope scope = ScopeFactory.CreateScope(); | |
try | |
{ | |
DbContext DbContext = scope.ServiceProvider.GetRequiredService<DbContext>(); | |
IConfiguration configuration = scope.ServiceProvider.GetRequiredService<IConfiguration>(); | |
List<EmailQueueItemEntity> emailQueueitems = await etbDbContext.EmailQueueItems | |
.Where(v => v.IsSent == false) | |
.OrderBy(v => v.Created) | |
.Take(5) | |
.ToListAsync(); | |
foreach (EmailQueueItemEntity emailQueueItem in emailQueueitems) | |
{ | |
// ... | |
await client.SendAsync(message); | |
emailQueueItem.IsSent = true; | |
await etbDbContext.SaveChangesAsync(); | |
} | |
} | |
catch (Exception ex) | |
{ | |
Log.Error(ex, "Issue Sending Email"); | |
} | |
} | |
} | |
catch (Exception ex) | |
{ | |
Log.Error(ex, "Issue Running PeriodicTimer"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment