Reputation: 3596
I have an app that relies around firing off events (phone calls) at specific times. I am using shared hosting so I can't just setup a windows service or cron job.
I have a URL such as /CheckCalls that queries if I have any calls scheduled +/- 60 seconds from now, and fires them off.
I call this via bash script regularly (or via cron service).
If, In a controller, I launch a new thread with a delay (e.g sleep(2000)) at the beginning of execution, can I expect it to be alive 2 seconds after the controller finishes, to fire off it's message?
This way I could a) avoid duplicates and b) ensure things went off at the correct time.
As below, Thread.Sleep() isn't realy the focus of my question. I've read up and used an alternative method, but the question still stands: If I am in a paid hosting environment somewhere, can I launch a background thread in a page that might live for 2 minutes, and expect it to execute?
Edit: I found this thread which deals with this topic, and uses HttpRuntime.Cache as a hack to implement this.
More interestingly perhaps, is a comment in the thread that states just what I was afraid of: the Timer won't keep the App Pool alive if nothing else is happening.
https://blog.stackoverflow.com/2008/07/easy-background-tasks-in-aspnet/
Upvotes: 2
Views: 154
Reputation: 14133
Here, this article explains how to handle something like what you need:
As AppPool will shut down itself once the site is idle for certain time, your scheduler would fail sometimes. Using http://www.uptimerobot.com, it will ping your web app every 5 minutes, so this will keep your AppPool alive.
Upvotes: 1
Reputation: 34844
Using Thread.Sleep is a poor design choice for several reasons:
1) It blocks the thread for the duration of the time it is sleeping. 2) It uses up threads in the thread pool, so this solution will not scale well at all. 3) It is a bad timing mechanism, because there is a time slice, or quantum, in play here that varies between operating systems and even versions of the same operating system (read: Windows).
This previous SO question gives more information about why Thread.Sleep is bad:
Why Is Thread.Sleep So Harmful
Upvotes: 2