What is the preferred method to manage a timed event with a Web application?
I'm designing an ASP.NET 4.0 Web application where administrators may create an auction with an expiration. The expiration time would be stored in a database. How can I ensure that the auction ends at the predetermined time, considering the开发者_JAVA百科 fact that an application instance may not be running when it is time? The application will be hosted with IIS7. I am considering Windows service, but I am wondering what other options are out there.
You can choose from two scenarios here:
- Lazy with the web application
- Active with a service
Lazy Scenario
Unless you have to interact instantly with the winner of an auction you could wait until the application starts and then let the application determine if there are any auctions that are expired. Collect them at that moment and handle them accordingly.
Active Scenario
Create a service that picks the first expiring auction from the DB. Store that DateTime and let the service sleep till the auction expires. Raise the service at that DateTime and process the expiring auction. Then let the service look for the next auction(s) to expire and let the service sleep again. And on and on.. I think The Windows Workflow Foundation contains all tools and requirements for this practice.
Something in between
Activate a scheduler that wakes up you web-app every hour/half hour/15 minutes and do the lazy stuff. Use a scheduler like HostMonitor.
A windows service that handles the timed events would be the best practice. Using a System.Threading.Timer in ASP.NET is bad juju; it MIGHT work in your case, because the change being made doesn't affect the UI directly, but I wouldn't bet on it working flawlessly. If you need to schedule events in the background of a web app, use a server app.
One thing to keep in mind; you may have hundreds or thousands of open auctions at a time. If you set a timer on every auction when it's opened, you'll have hundreds or thousands of sleeping threads managed by this server. I'd look only for auctions that would end before the next time you'd normally poll, and set timers for those auctions only. That would get you down to maybe a few dozen waiting threads. If you're writing the next eBay, though, even this will choke when you get hundreds of thousands, or millions, of auctions, and several hundred or thousand begin and end every minute.
If you want it to be 100% reliable, a Windows service that perform all scheduled logic is the way to go. As you say, you cannot trust a web application since it may not even be running.
精彩评论