java - 将异常捕获到 Spring Job 中

标签 java spring spring-boot

我使用此代码来运行 Spring 任务:

@Scheduled(fixedRate = 90000)
    public void myScheduler() throws Exception {

        ZonedDateTime zonedDateTime = ZonedDateTime.now(zone);

        DateTimeFormatter format = DateTimeFormatter.ofPattern("MMM d yyyy  hh:mm a");
        String time = zonedDateTime.format(format);

        System.out.printf("Scheduler exectuted (%s, (%s))\n", time, zone);

        TaskLogs task = new TaskLogs();
        task.setStatus("completed");
        task.setCreatedAt(LocalDateTime.now());
        task.setLog("Executing Notification Job");
        task.setTask_name("Executing Notification Job at " + time + " (" + zone + ")");

        taskLogsService.save(task);
    }

但有时我会遇到 SQL 错误。拦截错误的最佳方法是什么?我应该使用经典的 try-catch block 还是有一个任务监听器?

最佳答案

我建议在运行 @Schedule 时使用 try catch 和 SQLException 是最好的选择 - 可能你不想破坏它,

@Scheduled(fixedRate = 90000)
public void myScheduler() throws SQLException {

 ZonedDateTime zonedDateTime = ZonedDateTime.now(zone);

 DateTimeFormatter format = DateTimeFormatter.ofPattern("MMM d yyyy  hh:mm a");
 String time = zonedDateTime.format(format);

 System.out.printf("Scheduler exectuted (%s, (%s))\n", time, zone);

 TaskLogs task = new TaskLogs();
 task.setStatus("completed");
 task.setCreatedAt(LocalDateTime.now());
 task.setLog("Executing Notification Job");
 task.setTask_name("Executing Notification Job at " + time + " (" + zone + ")");
 try {
  taskLogsService.save(task);
 } catch (SQLException sqle){
 System.out.println(sqle);
 //or you can use slf4j logger to record same in logfile
 }
}

关于java - 将异常捕获到 Spring Job 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55724615/

相关文章:

java - 在 Java 中将带毫秒的字符串转换为日期格式

java 。集合中的通配符

eclipse - HTTP 500 - 无法为连接 URL '' 创建类 'null' 的 JDBC 驱动程序

java - 为什么我的内部对象的自定义 validator 不用于验证?

java - H2 org.h2.jdbc.JdbcSQLException 与正确的 DDL sql : error code = [42000-196]

java - 在构建的应用程序中获取资源

java - 通过 Java WebApp 使用 Runtime.exec 运行脚本

java - Spring Security正则表达式模式匹配器和 '/'字符

java - 如何通过spring boot在启动时配置 'dispatcherServlet'负载?

hibernate - Spring-boot & hibernate,使用事务