Search code examples
c#asp.net-corewindows-servicesbackgroundworker

Delete a Question Object from Database after 3 days if it is not answered


I'm working on a web application project using .net core and I want to self-close(delete) a Question object from the database(MySQL in my case) if it has been posted for 3 days with no answer. I believe I can use Worker Services but I'm not sure how to use it and if it's logical to have so many background services running in the background (1 service/timer for each question). Thank you.


Solution

  • You need just one background service for this job.

    I Assume that you already have a service interface:

    public interface IQuestionService {
        Task<IEnumerable<Question>> GetQuestionsToClose();
        Task CloseQuestions(IEnumerable<Question> questions);
    }
    

    Than you need to implement your background service:

    public CloseQuestionsBackgroundService : BackgroundService
    {
        private readonly IQuestionService questionService;
        public CloseQuestionsBackgroundService(IQuestionService questionService)
        {
            this.questionService = questionService;
        }
        protected override async Task ExecuteAsync(CancellationToken stopToken)
        {
          while (!stopToken.IsCancellationRequested)
          {
              var questionsToClose = questionService.GetQuestionsToClose().ConfigureAwait(false);
              if (questionsToClose.Any())
              {
                   await questionService.CloseQuestions(questionsToClose).ConfigureAwait(false);
              }
              await Task.Delay(Timespan.FromSeconds(10)).ConfigureAwait(false); // choose how much time between iterations
          }
       }
    }
    

    Now you just have to register the background service in the ConfigureService method of your Startup.cs

     services.AddHostedService<CloseQuestionsBackgroundService>();