tomcat 6 thread pool for asynchronous processing

前端 未结 3 873
迷失自我
迷失自我 2020-12-13 16:35

Short question: Within a Tomcat 6 app - how can I run a (separate) thread-pool?

What is the best solution for running a thread pool?

3条回答
  •  青春惊慌失措
    2020-12-13 17:19

    For your use case, you can utilize Timer and TimerTask available in java platform to execute a background task periodically.

    import java.util.Timer;
    import java.util.TimerTask;
    
    TimerTask dbTask = new TimerTask() {
        @Override
        public void run() {
            // Perform Db call and do some action
        }
    };
    
    final long INTERVAL = 1000 * 60 * 5; // five minute interval
    
    // Run the task at fixed interval
    new Timer(true).scheduleAtFixedRate(dbTask, 0, INTERVAL);
    

    Note, if a task takes more than five minutes to finish, subsequent tasks will not be executed in parallel. Instead they will wait in the queue and will be executed rapidly one after another when the previous one finishes.

    You can wrap this code in a singleton class and invoke from the startup servlet.

    Generally, its a good practice to perform these kinds of periodic background jobs outside of Servlet containers as they should be efficiently used serve HTTP requests.

提交回复
热议问题