Search code examples
c#asp.net.netasp.net-mvcscheduled-tasks

Repetitive tasks in specific time intervals?


For example, I want to call a function in specific time intervals (hourly or daily tasks.)

I m already using Timer. But it is working as long as my local server is working. For Example:

public static void StartYahooWeatherManager()
{
    Timer t = new Timer(1000 * 60 * 60 * 6  /* 6 hours */);
    t.Elapsed += new ElapsedEventHandler(WriteYahoWeatherRssItemToDb);
    t.Start();
}

private static void WriteYahoWeatherRssItemToDb(object o, ElapsedEventArgs e)
{
    YahooWeatherManager.InsertYahooWeatherRssItem(YahooWeatherManager.GetYahooWeatherRssItem());
}

I write weather info to db, in 6 hour intervals. Project is already in Host. Timer event is working as long as my computer local server is running.

Question:

What is the wrong about my code? (Or logical wrong to using timer in WebProject?) Why timer is only working while local server working?

What is the best way to manage time interval tasks? (not need asp.net)

I hope, I can explain the problem. Thanks.


Solution

  • The reason why the timer stops is because this timer runs in your ASP.NET application which itself is hosted on a web server. When this server stops or recycles the application, the AppDomain is brought down along with all threads you might have started. That's why it is a very bad idea to write repeating background tasks in an ASP.NET application. Phil Haack blogged about the dangers.

    The correct way to do this is to host this code in a separate process outside of your ASP.NET application. This could be a windows service or a console application which is scheduled to run at regular intervals using for example the Windows scheduler. This way the code is guaranteed to always run.