Scheduledcron = 0 0 23 每天23点执行 public void myTask 在这里执行你的数据库操作代码 Systemoutprintln定时任务执行; 1查询所有教练 ListCoach coachList = coachServicequeryAllCoaches; ListUpdateT
- Use try-with-resources to properly handle the resources used in the method.
try {
// code...
} catch (ParseException e) {
e.printStackTrace();
}
-
Instead of using
System.out.println()for logging, consider using a logging framework like SLF4J or Log4j. -
Move the logic for generating the next seven days outside the loop to avoid redundant computations.
List<String> sevenDays = RcqtUtils.getNextSevenDaysUn();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
- Avoid unnecessary database queries inside the loop by fetching all default times for coaches beforehand.
List<DefaultTime> defaultTimes = defaultTimeService.queryDefaultTimeByCoachIDs(coachList.stream().map(Coach::getCoachId).collect(Collectors.toList()));
- Use a
Mapto store the default times for each coach for easier lookup.
Map<Long, List<DefaultTime>> defaultTimesMap = defaultTimes.stream().collect(Collectors.groupingBy(DefaultTime::getCoachId));
- Iterate over the coaches and retrieve their default times from the
defaultTimesMap.
for (Coach coach : coachList) {
List<DefaultTime> defaultTimes = defaultTimesMap.get(coach.getCoachId());
// rest of the code...
}
- Use a
Setto store the dates that need to be checked for each coach to avoid duplicates.
Set<Date> datesToCheck = new HashSet<>();
for (String s : sevenDays) {
Date date = dateFormat.parse(s);
datesToCheck.add(date);
}
- Fetch all existing update times for the coaches and dates in a single query.
List<UpdateTime> existingUpdateTimes = updateTimeService.queryUpdateTimeByDates(coachList.stream().map(Coach::getCoachId).collect(Collectors.toList()), datesToCheck);
- Use a
Setto store the dates for which update times have already been generated.
Set<Date> generatedDates = new HashSet<>();
for (UpdateTime updateTime : existingUpdateTimes) {
generatedDates.add(updateTime.getCourseDate());
}
- Generate new update times for the remaining dates.
List<UpdateTime> newUpdateTimes = new ArrayList<>();
for (Coach coach : coachList) {
List<DefaultTime> defaultTimes = defaultTimesMap.get(coach.getCoachId());
for (String s : sevenDays) {
Date date = dateFormat.parse(s);
if (!generatedDates.contains(date)) {
// generate new update times
// rest of the code...
}
}
}
- Batch insert the new update times using
saveBatch().
boolean success = updateTimeService.saveBatch(newUpdateTimes);
``
原文地址: http://www.cveoy.top/t/topic/hNw5 著作权归作者所有。请勿转载和采集!