I have a Blazor Server .Net 6 app. I have a function in this app that I would like to be called every hour. In the past I have created a Windows Server Scheduled Task to call a web page that executes the function. I was wondering if there was any nice assemblies/methods I could add to my app that would allow me to do this instead. The other alterantive was to create an Azure Function but I thought i would investigate what I can do within the relms of my Blazor Server App first.
TIA
CodePudding user response:
You can use a custom service with a timer for this. For example:
public class ExampleService : IDisposable
{
public Timer? CheckTimer { get; set; }
public async Task RunTimer()
{
CheckTimer = new Timer(async (e) =>
{
try
{
await Check();
}
catch (Exception ex)
{
}
},null,0, 30000); // define interval here
}
public async Task Check()
{
// DO YOUR STUFF HERE
}
public void Dispose()
{
CheckTimer.Dispose();
}
}
In your Program.cs start the service:
await builder.Services.GetRequiredService<ExampleService>().RunTimer();