Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scheduling Web Api method to run on set intervals

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 hitting the desired controller method.

I was wondering whether this is possible to automate in the Web Api project itself, rather than using an external service. So far I have not found any documentation on doing this.

Apologies for not having a code sample to work from as I have not found a base to start from yet.

like image 961
Thewads Avatar asked Mar 13 '13 11:03

Thewads


People also ask

How do I automatically run a webservice?

You can do it in several ways but simplest would be write a console App (or even a PowerShell Script) to call web service and use Windows Scheduler to configure running at specific time.

What is schedule API?

Project schedule APIs provide the ability to perform create, update, and delete operations with Scheduling entities. These entities are managed through the Scheduling engine in Project for the web.


2 Answers

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.

like image 190
Ionian316 Avatar answered Oct 06 '22 09:10

Ionian316


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.

like image 25
JustAnotherUserYouMayKnow Avatar answered Oct 06 '22 09:10

JustAnotherUserYouMayKnow