Preview:
//UserDeletionService.cs
using av_motion_api.Data; // Adjust the namespace to match your project
using av_motion_api.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;

namespace av_motion_api.Services
{
    public class UserDeletionService : IHostedService, IDisposable
    {
        private readonly IServiceProvider _serviceProvider;
        private Timer _timer;

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

        public Task StartAsync(CancellationToken cancellationToken)
        {
            _timer = new Timer(DeleteDeactivatedUsers, null, TimeSpan.Zero, TimeSpan.FromMinutes(0));
            return Task.CompletedTask;
        }

        private void DeleteDeactivatedUsers(object state)
        {
            using (var scope = _serviceProvider.CreateScope())
            {
                var context = scope.ServiceProvider.GetRequiredService<AppDbContext>();
                var userManager = scope.ServiceProvider.GetRequiredService<UserManager<User>>();

                var sixMonthsAgo = DateTime.UtcNow.AddMonths(-6);

                var usersToDelete = context.Users
                    .Where(u => u.User_Status_ID == 2 && u.DeactivatedAt < sixMonthsAgo)
                    .ToList();

                foreach (var user in usersToDelete)
                {
                    userManager.DeleteAsync(user).Wait();
                }

                context.SaveChanges();
            }
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            _timer?.Change(Timeout.Infinite, 0);
            return Task.CompletedTask;
        }

        public void Dispose()
        {
            _timer?.Dispose();
        }
    }
}
//program.cs
builder.Services.AddHostedService<OrderStatusUpdater>();
downloadDownload PNG downloadDownload JPEG downloadDownload SVG

Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!

Click to optimize width for Twitter