ScheduledExecutorService Exception handling

前端 未结 7 2058
再見小時候
再見小時候 2020-11-28 22:57

I use ScheduledExecutorService to execute a method periodically.

p-code:

ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecu         


        
7条回答
  •  旧巷少年郎
    2020-11-28 23:24

    You should use the ScheduledFuture object returned by your scheduler.scheduleWithFixedDelay(...) like so :

    ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
    ScheduledFuture handle =
            scheduler.scheduleWithFixedDelay(new Runnable() {
                 public void run() { 
                     throw new RuntimeException("foo");
                 }
            }, 1, 10, TimeUnit.SECONDS);
    
    // Create and Start an exception handler thread
    // pass the "handle" object to the thread
    // Inside the handler thread do :
    ....
    try {
      handle.get();
    } catch (ExecutionException e) {
      Exception rootException = e.getCause();
    }
    

提交回复
热议问题