Scheduling Web Api method to run on set intervals

后端 未结 4 2404
夕颜
夕颜 2021-02-20 00:58

In my current project there is a need to schedule a method to run at set intervals e.g. once a week, and currently this is done via a windows service creating an HttpClient and

相关标签:
4条回答
  • 2021-02-20 01:11

    There is not really a way within the Web Api to achieve what you desire. Web Apis should be stateless anyway.

    You could theoretically create a long-running task on your web server to periodically call your Api (or the method directly), the best place to put such a method would be the OnStart method within your global asax file. However, this method is run when the web server is loaded into the app-domain, and the task will be killed when the web server decides to unload your application. So if you don't call your web server at least once, your task won't be started. And if your web server is not access periodically, your task will be killed.

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

    0 讨论(0)
  • 2021-02-20 01:20

    I'm not saying 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 utilized the moment.js library. There's a timer/countdown feature available. I set it to fire every hour and make the call to our API. Had it working on IIS. It was at my previous employer otherwise I would post the actual code.

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

    0 讨论(0)
  • This is not something you want the Web API to do, and I don't think it does. Something about single responsibilities.

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

    0 讨论(0)
  • 2021-02-20 01:35

    If you need to schedule a background task to run every week, you can use FluentScheduler (NuGet link) to run 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 changed the API slightly. The task should now be derived from IJob, not ITask. Updated my example to reflect this.

    0 讨论(0)
提交回复
热议问题