简体   繁体   English

如何动态启动和结束tomcat servlet请求中的计时器或计划作业?

[英]How to start and end a timer or schedule job in tomcat servlet request dynamicly?

Many posts said we can use ScheduledExecutorService in a ServletContextListener . 许多帖子说我们可以在ServletContextListener使用ScheduledExecutorService 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? 例如,在客户端A的请求A中启动计时器,在客户端A或客户端B的请求B中停止计时器。我是否应该将计时器存储在会话中?

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. 真正的问题是:我是根据网络请求创建订单的,如果24小时后仍未付款,我想取消订单。

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. 为了清楚起见,我假设是这样的情况:我从Web请求中创建了一个对象,如果10秒钟后仍未处理该对象,我想删除该对象。 In such little time, was it good to run a schedule job like each 5 or 8 seconds? 在这么短的时间内,像这样每5或8秒运行一次调度作业是否很好? I wanna do the job precisely after 10 seconds or even 1 second. 我想在10秒甚至1秒后精确地完成工作。

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. 通常,这种事情将作为计划的后台任务完成,该任务将检查您的订单存储库中是否有已过期且需要取消的订单,您不需要为此使用HTTP会话。

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. 在您的Order类中,您可以添加一个属性,该属性是在请求A中创建时的时间戳,这将有助于查找它们。

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 有关ScheduledExecutorService的Javadocs中的更多详细信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM