i am implementing a background service , the problem is when i run it in local it is working fine since the app is hit and running . but in iis i deployed code and started the server in iis. the background service is not running until i browse the site and becoming idle when the server is idle
My program. cs builder.Services.AddHostedService();
i have registered it also
the main problem is i cant create a windows service or a console app since i it is not approved in my org.
```
using DocumentFormat.OpenXml.InkML;
using DocumentFormat.OpenXml.Office2016.Drawing.ChartDrawing;
using handbook.Controllers.HR;
using handbook.Data;
using handbook.Models.Mail;
using handbook.Repositories.Implementation;
using handbook.Repositories.Interface;
using handbook.ViewModel;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System.Configuration;
using System.Globalization;
using System.Linq;
namespace handbook.BackgroundmailService
{
public class EmailReminderSenderService : IHostedService, IDisposable
{
public static IConfiguration Configuration { get; set; }
private Timer _timer;
private readonly IOauthMailService _emailSender;
private readonly ILogger<EmailReminderSenderService> _logger;
public EmailReminderSenderService(IOauthMailService emailSender, ILogger<EmailReminderSenderService> logger, IServiceProvider serviceProvider, IConfiguration configuration)
{
_emailSender = emailSender;
_logger = logger;
Services = serviceProvider;
Configuration = configuration;
}
public IServiceProvider Services { get; }
private static TimeSpan getJobRunDelay()
{
// Change the delay to run every 10 minutes
return TimeSpan.FromMinutes(1);
}
public void Dispose()
{
_timer?.Dispose();
}
public Task StartAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("Background service is started");
_timer = new Timer(SendEmails, null, getJobRunDelay(), getJobRunDelay());
return Task.CompletedTask;
}
public async void SendEmails(object state)
{
my task
}
public Task StopAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("Background service is stopping");
_timer?.Change(Timeout.Infinite, 0);
return Task.CompletedTask;
}
}
}
```
IIS typically does not start background services on its own, it relies on requests that trigger application startup. Currently, you can configure IIS to always run the site, but this is not a good workaround.
To keep a background service running, you may want to look for alternatives; after all, IIS is designed for hosting Web applications, not long-running background services.
You mentioned that your organization doesn't approve the creation of Windows services, but you may want to discuss this with your IT department. Hosting an application as a Windows service is the most common way to run a long-lived background process on a Windows computer.