I want to call a service after 1 minute, or 10 minutes. I have store frequency (frequency is a number of days like 1 minute, 10 minutes) in the table context of a user. So user store data with a 1-week frequency so messages every week in the .net core
Loading

Rajkiran SwainRank #165 · 14.4K reputationPosted May 22, 2023, 11:47 AM EDT
using System; using System.Threading; public class Scheduler { private Timer timer; public void ScheduleServiceCall(int frequencyInMinutes) { TimeSpan delay = TimeSpan.FromMinutes(frequencyInMinutes); TimeSpan interval = TimeSpan.FromMinutes(frequencyInMinutes); timer = new Timer(ExecuteServiceCall, null, delay, interval); } private void ExecuteServiceCall(object state) { // Put your service call code here // The service call will be executed based on the specified frequency } }Mohamed Azarudeen ZRank #297 · 8.5K reputationPosted May 22, 2023, 9:45 AM EDT
Hi sunny for that
Create a Background Service:
using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using System; using System.Threading; using System.Threading.Tasks; public class MyBackgroundService : BackgroundService { private readonly ILogger _logger; public MyBackgroundService(ILogger logger) { _logger = logger; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { // Get the user's stored frequency from the database or context var frequencyInMinutes = GetUserFrequency(); // Replace with your logic to retrieve the frequency // Wait for the specified interval await Task.Delay(TimeSpan.FromMinutes(frequencyInMinutes), stoppingToken); // Perform the desired logic here, such as calling the service await CallService(); // Log the execution _logger.LogInformation("Service called successfully."); } } private Task CallService() { // Replace with your logic to call the desired service // You can use HttpClient or any other method to make the API call throw new NotImplementedException(); } private int GetUserFrequency() { // Replace with your logic to retrieve the user's stored frequency // This could be from a database query or any other data source throw new NotImplementedException(); } }register the service
public void ConfigureServices(IServiceCollection services) { // ... services.AddHostedService(); // ... }and config ythe dependency injection'
public void ConfigureServices(IServiceCollection services) { // ... services.AddHttpClient(); // ... }Vishal JoshiRank #377 · 6.7K reputationPosted May 22, 2023, 10:56 AM EDT
Hello
Please check out my below article for the same.
https://www.c-sharpcorner.com/article/create-window-service-in-net-core/
Thanks
Vishal