Reputation: 73908
I have an web application in MVC 3 and C#.
I need run a method every 1 hour for an unlimited time. I would like to know how to implemented it.
Thansk.
Related
Call MVC Controller from Windows task scheduler
Upvotes: 3
Views: 9100
Reputation: 3364
Best thing to do is use Azure Functions. It was designed for exactly this problem. It's actually pretty good. You can run a scheduled task whenever you like using a timer trigger.
https://learn.microsoft.com/en-us/azure/azure-functions/functions-overview
Upvotes: -1
Reputation: 4500
Darin is correct, however, if you had to do it in your app, here's how you would go about it:
In Global.asax.cs
static void ScheduleTaskTrigger()
{
HttpRuntime.Cache.Add("ScheduledTaskTrigger",
string.Empty,
null,
Cache.NoAbsoluteExpiration,
TimeSpan.FromMinutes(60), // Every 1 hour
CacheItemPriority.NotRemovable,
new CacheItemRemovedCallback(PerformScheduledTasks));
}
static void PerformScheduledTasks(string key, Object value, CacheItemRemovedReason reason)
{
//Your TODO
ScheduleTaskTrigger();
}
void Application_Start(object sender, EventArgs e)
{
ScheduleTaskTrigger();
}
Upvotes: 4
Reputation: 1038710
You could use a System.Timers.Timer. But please notice that implementing recurring background tasks in ASP.NET applications is a perilous task. Don't forget that IIS could recycle the application pool at any time and under some circumstances (period of inactivity on the site, CPU/Memory thresholds are reached, ...) bringing down all background tasks you might have started.
The correct way to do this is to implement it in another application. This could for example be a Windows Service or a simple Console Application scheduled to run at regular intervals with Windows Scheduler.
Upvotes: 10