Muhammed Caylak
Muhammed Caylak

Reputation: 363

How do I call a function automatically in the API?

Hello everyone

I wrote an API using Asp.Net Core .I want a function to run automatically every 10 minutes. How can I do such a thing?

I need your help . Thanks in advance.

public void AutoUpdate()
{
   var startTimeSpan = TimeSpan.Zero;
   var periodTimeSpan = TimeSpan.FromMinutes(10);
   var dbData = _provinceDataDal.GetAll();

   var timer = new System.Threading.Timer((e) =>
   {
     UpdateData(dbData);
   }, null, startTimeSpan, periodTimeSpan);
}

I used a method like use but it didn't work as I wanted. Because it works only once.

I want it to run my updateData function above for 10 minutes without having to trigger it when the API first runs and again.

Upvotes: 0

Views: 2265

Answers (2)

krlosmederos
krlosmederos

Reputation: 196

Since asp.net core 2.1 are the background tasks with hosted services.

First, configure the services in Startup

public IServiceProvider ConfigureServices(IServiceCollection services)
{
   //Other DI registrations;

   // Register Hosted Services
   services.AddHostedService<MyServices>();
}

After, you implement the ExecuteAsync method with the code of what you want to do

    public class MyServices : BackgroundService
    {
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            _logger.LogDebug("Starting");

            stoppingToken.Register(() =>
                _logger.LogDebug("Stopping."));

            while (!stoppingToken.IsCancellationRequested)
            {
                _logger.LogDebug($"Working");

                // Your code here

                await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken);
            }

            _logger.LogDebug($"Stopping.");
        }
   }

More documentation in this link's Microsoft

Upvotes: 3

Lukasz Szczygielek
Lukasz Szczygielek

Reputation: 3129

You are looking for IHostedService. Example with timer you can find here - Timed background tasks. Keep in mind that it is good to use a BackgroundService base class during implementation.

Upvotes: 1

Related Questions