我使用以下代码运行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块还是该任务有一个侦听器?
最佳答案
我建议在SQLException上使用try catch最好,因为您正在运行@Schedule-可能您不想破坏它,
@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
}
}