Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a thread that runs all the time in the background in a .net web site?

I intend to build a small web site that will poll a third party web service, say every 15 minutes, store the collected data in a db and display the results via web pages.

I want the polling to run 24 hours a day with or without anyone visiting the web site.

I know I could create a stand alone application that could run on the server to do this but is there a clean way to incorporate this into the website code. I need something that would be easy to deploy on a cheep 3rd party hosting site.

Any pointers in the right direction will be welcome.

Thanks

like image 669
Magpie Avatar asked Feb 05 '09 11:02

Magpie


2 Answers

Add a global.asax file to your website project.

This will give you four event handlers, one of which is used when you application loads.

You can fire off your thread here.

Additionally, I recommend that you set the threads to background so that you can have them dissappear when you close your web app.

System.Threading.Thread.CurrentThread.IsBackground = true;
like image 195
Spence Avatar answered Oct 12 '22 11:10

Spence


You ideally need to create a Windows Service to do it. The other suggestion of creating threads from the application startup is fine until you web server gets rebooted.

At that point your background task won't be kicked off until the next person visits the site. With a Windows Service the background tasks will start running again as soon as the server boots.

Creating a Windows Service using .net is fairly straight forward, certainly a lot easier than it was before .net:

http://www.codeproject.com/KB/system/WindowsService.aspx

You could of course fudge the other solution by getting something to run to hit your website after the server boots, but that is hacky and the "proper" way is a Windows Service.

Edit:

That'll teach me to read the question properly, didn't spot the requirement about working on a cheap shared host. The other solution is probably the best that you can hope for in that case as the Windows Service approach is almost certainly not possible.

like image 45
andynormancx Avatar answered Oct 12 '22 09:10

andynormancx