Planning an Api web method to run at set intervals

In my current project, there is a need to plan a method that will run at set intervals, for example. once a week, and currently this is done using the Windows service that creates the HttpClient and uses the desired controller method.

I was wondering if it is possible to automate the Web Api project itself rather than use an external service. So far I have not found any documentation about this.

Apologizes for the fact that I did not have a sample code from which I have not yet found the database.

+9
source share
4 answers

If you need to schedule a background task to run every week, you can use the FluentScheduler ( NuGet link ) to launch it for you. You can do something like this:

public class WeeklyRegistry : Registry { public WeeklyRegistry() { Schedule<WeeklyTask>().ToRunEvery(1).Weeks(); // run WeeklyTask on a weekly basis } } public class WeeklyTask : IJob { public void Execute() { // call the method to run weekly here } } 

Update . The new version of FluentScheduler has slightly changed the API. Now the task should be taken from IJob, and not from ITask. Updated my example to reflect this.

+10
source

Inside web api there is no way to get what you want. In any case, Web Apis should be stateless.

Theoretically, you can create a long-term task on your web server to periodically call your Api (or method directly), the best place to put such a method would be the OnStart method in your global asax file. However, this method is started when the web server is loaded into the application domain, and the task will be destroyed when the web server decides to unload your application. Therefore, if you do not call your web server at least once, your task will not be launched. And if your web server does not access periodically, your task will be killed.

Having an external reliable resource, such as your service, is still the best and safest.

+3
source

This is not what you want the web API to execute, and I don't think so. Something about common responsibilities.

What is wrong with the service approach? You can also take a look at the Windows Task Scheduler.

+2
source

I am not saying that this is the best approach, but it worked for me, and it was pretty easy.

Our WebApi was already in place, and I needed a quick solution to call the API once an hour. I used node.js and wrote a few lines of code that used the moment.js library. There is a timer / countdown function. I turn it on every hour and call our API. Did it work on IIS. This was from my previous employer, otherwise I would publish a valid code.

It was easy, and it worked. Hope this helps someone. library node.js + moment.js .

0
source

All Articles