开发者

How to auto execute a function at server side

开发者 https://www.devze.com 2023-03-29 11:19 出处:网络
Recently I was creating an auction site. I want to make it like when user bid the item, there is a AI bidder to upbid the开发者_如何学C user. For say user bid on item1 after 5 seconds the AI bidder wi

Recently I was creating an auction site. I want to make it like when user bid the item, there is a AI bidder to upbid the开发者_如何学C user. For say user bid on item1 after 5 seconds the AI bidder will auto bid the item1 as well. Any idea how can I execute it automatically after 5 seconds?


A simple and efficient solution could be to store all future bids with a "due date" and all the information to bid in a list. Then every 5 seconds or so you could loop through the list and make all bids if they are due. This system would be extensible and would work for a large amount of bids. Of course, ideally this would run in a different thread.

It's a bit like re-implementing a "cron-like" job management in your servlet but I can't see any solution that would fit your needs out of the box.

I am not sure I answered your question, hope so.

Regards, Stéphane


Depends on what technology you actually use, you can use EJB timers for that for example, just start the timer ejb when a new bid occurs, on timer timeout (after some time) the method executes and updates the bid.


Standard servlet solution

  1. Create a Filter, map it to the url pattern of your bid servlet.
  2. In your doFilter(), after your filterChain.doFilter() call (ie, after the request has been processed by the servlet/JSP), schedule an action for 5 seconds in the future (you can use the standard java ScheduledExecutorService)
  3. In the Runnable implementation you schedule (your task), place the AI bid.


In my opinion:

  1. If user bid, and after 5 secs, it sends the request to the server, i prefer JS with setTimeout(). (Of course it required Browser's JS - read more abt this in W3School).
  2. Otherwise, you can use an array (or smt like that) act as an queue (in server side), after each 5 secs, it's lock the queue (sync), and check for which inserted 5 secs ago, and process it (or use an Thread for each time an event requests to server). Basically, you can use a thread to do that trick? (Did u mean this?).
0

精彩评论

暂无评论...
验证码 换一张
取 消