I’m currently working on an e-commerce site and there’s one feature that i’m not very sure how to implement. Most of the time you just add product(s) to your cart and buy them, that’s probably the simplest workflow. What i’m asking is a little different, what if there’s a time limit for a product to buy ? I mean some sites give you an exact time limit to buy a product (like Soccer Manager), in those sites you can’t hold a product forever, there’s a 15 minutes limit for it and if you dont buy in that period, item will be released from your cart. (and most probably someone else will jump on it)
Now, as an ASP.NET MVC programmer i’d love to implement this feature but as i said, i’m not sure how to do it. I think when i add item to cart i need to hold the time (something like ItemAddedAt) and i need to release that item in x minutes so something needs to run x minutes later to release that product. Globally thinking, i think i need a service, when i add an item, i also need to subscribe it to this service and service runs a timer/job in the background. What i dont know/have no experience is this part, how to do that in an ASP.NET MVC project, is there a sample project, article, library or something like that ?
Of course i dont know if my logic is right for this problem, i need some guidance, if possible some source code to work on.
AFAIK there are no standard way to declare/program tasks within an MVC project. The recommended way to accomplish what you want would be to create a new Console Application project within your solution, and use the Windows Task Scheduler to execute every X minutes, releasing any products that have been more than X minutes in any cart.
For this to work, you will need to reference your MVC project from the new one (to get access to all the models) or, even better, create a Class Library project, move your Model/database classes there, and reference it from the MVC and Console projects.
All that being said, there is actually a small “hack” that can be used to get programmed tasks in an MVC project. You can use the following code:
That line, that could be called, for example, from the Global.asax, would add a “Task” entry to the cache. The value stored (“1”) is not important, the important thing is that the cache entry expires in five minutes and, when expired, calls the “CheckCarts” method (defined in the Global.asax, or in the class were you execute this code).
When the cache expires, the CheckCarts method is called, your code does whatever it has to do, and in the end adds itself to the Cache again, to be called in another 5 minutes.