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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With