Porting code from using timers to scheduledexecutorservice

前端 未结 3 1352
终归单人心
终归单人心 2021-01-15 16:31

I am trying to port code from using java timers to using scheduledexecutorservice

I have the following use case

class A {

    public boolean execut         


        
3条回答
  •  [愿得一人]
    2021-01-15 17:23

    There is currently no good way to handle repeating tasks in the Executors framework.

    It really wasn't designed with this use case in mind, and there is no realistic way to avoid swallowing exceptions.

    If you really must use it for repeating tasks, each scheduling should look something like this:

    scheduler.scheduleWithFixedDelay(new Runnable() {
      public void run() {
         try {
           .. your normal code here...
         } catch (Throwable t) {
           // handle exceptions there
         }
      }
    }, period, delay);
    

提交回复
热议问题