java/spring scheduler 异常捕获处理
来源:互联网 发布:闪电网络 时间 编辑:程序博客网 时间:2024/06/05 19:39
由于java的异常会导致线程被打断,因此任务的异常是被任务工作线程捕获的。
若需要对任务运行情异常捕获可以这样操作:
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();}
或者直接在任务中捕获处理:
final Runnable someChoreRunnable = () -> { try { doChore(); } catch ( Throwable t ) { // Catch Throwable rather than Exception (a subclass). logger.error( "Caught exception in ScheduledExecutorService. StackTrace:\n" + t.getStackTrace() ); }};
spring通过注解的方式可以通过scheduler的setErrorHandler处理:
@EnableScheduling@Configurationclass SchedulingConfiguration implements SchedulingConfigurer { private final Logger logger = LoggerFactory.getLogger(getClass()); private final ThreadPoolTaskScheduler taskScheduler; SchedulingConfiguration() { taskScheduler = new ThreadPoolTaskScheduler(); taskScheduler.setErrorHandler(t -> logger.error("Exception in @Scheduled task. ", t)); taskScheduler.setThreadNamePrefix("@scheduled-"); taskScheduler.initialize(); } @Override public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { taskRegistrar.setScheduler(taskScheduler); }}
亦是在代码中直接try-catch:
@Scheduled(cron = "${schedulerRate}")public void scheduledJob() { try { businessLogicService.doBusinessLogic(); } catch (Exception e) { log.error(e); }}
阅读全文
0 0
- java/spring scheduler 异常捕获处理
- java处理未捕获异常
- JAVA处理未捕获异常
- java之异常的捕获及处理
- Java线程未捕获异常处理
- Java 异常处理的捕获形式
- java之异常捕获及处理
- 3、Java 异常的捕获及处理
- java中的异常捕获及处理
- Java线程未捕获异常处理
- java-未捕获异常的处理
- java异常的捕获及处理
- Java中的异常处理:何时抛出异常,何时捕获异常?
- java异常处理机制示例(java抛出异常、捕获、断言)
- java异常处理机制示例(java抛出异常、捕获、断言)
- 全局异常捕获处理
- 异常捕获处理
- 《异常捕获及处理》
- mybatis中association的使用
- 金蝶建立账套时报 “ 在对应所需名称或序数的集合中,未找到项目 ”解决方法
- java中HashTable和HashMap的区别
- Java的stream流操作
- 11月10日笔记心得
- java/spring scheduler 异常捕获处理
- 最小生成树
- javaScript ,jQuery ,Ajax ,json 之间的关系
- kali linux 生成后门文件命令:PHP,java,Linux,windows,android
- href 与 click 事件执行顺序
- 3nextElementSibling
- react-thunk迁到redux-saga,他们的对比
- redis的安装与使用
- Windows+Linux+Mac操作系统常用操作记录