Trouble with Running a Continuous Task in the Background

26 views Asked by At

I want to add notifications at certain intervals using BackgroundService, but the waiting interval I set is 10 seconds in this example, the program running ends when it is finished.

Service like this:

public class BackGroundWorkerService : BackgroundService
     {
         private readonly IServiceProvider _serviceProvider;

         public BackGroundWorkerService(IServiceProvider serviceProvider)
         {
             _serviceProvider = serviceProvider;
         }

         protected override async Task ExecuteAsync(CancellationToken stoppingToken)
         {
             while (true)
             {
                 using (var scope = _serviceProvider.CreateScope())
                 {
                     var notificationService = scope.ServiceProvider.GetRequiredService<INotificationService>();
                     var notificationMessage = NotificationMessageService.GetMessage(
                         NotificationMessageTypes.Added,
                         TableNamesConstants.Expenses,
                         "AA"
                     );

                     await notificationService.AddAsync(notificationMessage, "Notification Title | Try", userId: 1);

                     Thread.Sleep(TimeSpan.FromSeconds(10));
                 }
             }
         }
     }

Here's the configuration in Program.cs:

  public static IHostBuilder CreateHostBuilder(string[] args) =>
         Host.CreateDefaultBuilder(args)
             .ConfigureWebHostDefaults(webBuilder =>
             {
                 webBuilder.UseStartup<Startup>();
             }).ConfigureLogging(logging =>
             {
                 logging.ClearProviders();
             }).ConfigureServices((hostContext, services) =>
             {
                 services.AddHostedService<BackGroundWorkerService>(); // Add background service
             });`

Additional info:

await notificationService.AddAsync(notificationMessage, "Notification Title | Try", userId: 1);

If I don't write the line, the problem disappears, but my goal is to add it anyway. I thought about whether it is related to the unitOfWork structure, etc. But I do not throw the global error page. it ends the work directly, I couldn't understand the reason.

I want to add notifications at certain intervals using BackgroundService.

0

There are 0 answers