5

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.

Rui Jarimba
  • 11,166
  • 11
  • 56
  • 86
AliRıza Adıyahşi
  • 15,658
  • 24
  • 115
  • 197

3 Answers3

7

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.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
2

My suggestion is to create a Windows service that uses a timer, or create a normal application and create a scheduled task to run it in the interval you need. This StackOverflow post may help you:

Windows service and timer

Community
  • 1
  • 1
Rui Jarimba
  • 11,166
  • 11
  • 56
  • 86
0

You can disable recycling for the application pool your asp.net app belongs to. Memory leaks are rare for .Net so you can rely on GC most of the time. This will also remove warmup after recycling and improve user experience with almost no effort.

The other good solution is to create console application and schedule it in windows "Task Scheduler". You will have nice UI to manage when and how to run. It is much easier to maintain such tasks than "Windows Service" and requires to write less code.

Suraj Singh
  • 4,041
  • 1
  • 21
  • 36