Homeautomation/src/main/java/de/ph87/homeautomation/schedule/ScheduleExecutionService.java

49 lines
1.7 KiB
Java

package de.ph87.homeautomation.schedule;
import de.ph87.homeautomation.property.PropertyWriteService;
import de.ph87.homeautomation.schedule.entry.ScheduleEntry;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.ZonedDateTime;
import java.util.Comparator;
@Slf4j
@Service
@Transactional
@RequiredArgsConstructor
public class ScheduleExecutionService {
private final ScheduleReadService scheduleReadService;
private final ScheduleCalculationService scheduleCalculationService;
private final PropertyWriteService propertyWriteService;
public void executeAllLastDue() {
final ZonedDateTime now = ZonedDateTime.now();
scheduleReadService.findAll().forEach(schedule -> executeLastDue(schedule, now));
}
private void executeLastDue(final Schedule schedule, final ZonedDateTime now) {
if (schedule.getProperty() == null) {
log.error("Cannot execute Schedule {}: No property set!", schedule);
return;
}
schedule.getEntries().stream()
.filter(entry -> entry.getNextFuzzyTimestamp() != null && !entry.getNextFuzzyTimestamp().isAfter(now))
.max(Comparator.comparing(ScheduleEntry::getNextFuzzyTimestamp))
.ifPresent(entry -> executeEntry(schedule, entry, now));
}
private void executeEntry(final Schedule schedule, final ScheduleEntry entry, final ZonedDateTime now) {
entry.setLastClearTimestamp(entry.getNextClearTimestamp());
log.info("Executing Schedule \"{}\" Entry {}", schedule.getTitle(), entry);
propertyWriteService.write(schedule.getProperty(), entry.getValue());
scheduleCalculationService.calculateSchedule(schedule, now);
}
}