55 lines
2.0 KiB
Java
55 lines
2.0 KiB
Java
package de.ph87.homeautomation.schedule;
|
|
|
|
import de.ph87.homeautomation.bulk.BulkExecutor;
|
|
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 ScheduleReader scheduleReader;
|
|
|
|
private final ScheduleCalculationService scheduleCalculationService;
|
|
|
|
private final PropertyWriteService propertyWriteService;
|
|
|
|
private final BulkExecutor bulkExecutor;
|
|
|
|
public void executeAllLastDue() {
|
|
final ZonedDateTime now = ZonedDateTime.now();
|
|
scheduleReader.findAll().forEach(schedule -> executeLastDue(schedule, now));
|
|
}
|
|
|
|
private void executeLastDue(final Schedule schedule, final ZonedDateTime now) {
|
|
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) {
|
|
log.info("Executing Schedule \"{}\" Entry {}", schedule.getTitle(), entry);
|
|
entry.setLastClearTimestamp(entry.getNextClearTimestamp());
|
|
scheduleCalculationService.calculateSchedule(schedule, now);
|
|
if (entry.getProperty() != null) {
|
|
log.debug("Schedule setting property: {} = {}", entry.getProperty().getTitle(), entry.getValue());
|
|
propertyWriteService.writeToChannel(entry.getProperty(), entry.getValue());
|
|
}
|
|
if (entry.getBulk() != null) {
|
|
log.debug("Schedule executing Bulk: {}", entry.getBulk());
|
|
bulkExecutor.execute(entry.getBulk());
|
|
}
|
|
}
|
|
|
|
}
|