gpt4 book ai didi

java - 将异常捕获到 Spring Job 中

转载 作者:行者123 更新时间:2023-12-02 09:59:47 27 4
gpt4 key购买 nike

我使用此代码来运行 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com