0

Many posts said we can use ScheduledExecutorServicein a ServletContextListener. But I want to start a timer at some kind of circumstance, and then stop it at another circumstance. For example, start a timer in request A from client A, stop it in request B from client A or client B. Should I store the timer in session or not?

The real problem is this: I create an order from a web request, I wanna cancel the order if it hasn't been paid after 24 hours.

To make things clear, I suppose the situation like this: I create an object from a web request, I wanna delete the object if it hasn't been handled after 10 seconds. In such little time, was it good to run a schedule job like each 5 or 8 seconds? I wanna do the job precisely after 10 seconds or even 1 second.

Leo Lee
  • 468
  • 5
  • 16

1 Answers1

0

Normally this kind of thing would be done as a scheduled background task that would check your repository of orders for those that have expired and need to be cancelled, you should not need to use the HTTP session for this.

In your Order class you can add a property that is the timestamp when it was created in request A that would help in looking them up.

Then create a scheduler:

ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

Create a Runnable task that will check for old orders that need cancelling:

Runnable cancelUnpaidOrdersTask = new Runnable() {
        public void run() {
            // Your code to look for orders where the timestamp is older than 24 hours and then cancel them.
        }
    };

Then run this task every minute - or however often you feel you would need to check based on your own requirements.

    scheduler.scheduleAtFixedRate(cancelUnpaidOrdersTask, 0, 1, TimeUnit.MINUTES);

More details in the Javadocs for ScheduledExecutorService

tchambers
  • 456
  • 3
  • 5
  • This answer here explains how you can instantiate an executor service from within a web context: http://stackoverflow.com/a/9186070/2892670 – tchambers Jul 27 '16 at 10:58
  • Thanks. But I want something different. I edit my question to make it clear. – Leo Lee Jul 28 '16 at 02:32
  • I'm not sure that it's a very good design, but you could use a [PassiveExpiringMap](https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/map/PassiveExpiringMap.html) to store the objects - presumably you will need some kind of ID or key to look them up anyway. Guava has a similar concept in [CacheBuilder](https://google.github.io/guava/releases/17.0/api/docs/com/google/common/cache/CacheBuilder.html) where you can use the '.expireAfterWrite(10, TimeUnit.SECONDS)' method during building. – tchambers Jul 28 '16 at 08:41