package com.energy.online.data.crontab; import com.energy.online.data.OnlineDataMain; import com.energy.online.data.common.CommonData; import com.energy.online.data.dto.BaseConfig; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import wei.yigulu.iec104.util.SendDataFrameHelper; import java.io.BufferedWriter; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.text.SimpleDateFormat; import java.util.List; import java.util.Map; import java.util.stream.Collectors; @Component @Slf4j public class TimeSaveScheduled { private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); @Autowired private BaseConfig baseConfig; // @Scheduled(cron = "0/1 * * * * *") @Scheduled(cron = "${my.scheduled.cron}") public void collectData() { CommonData.addList(); } @Scheduled(cron = "0 0/2 * * * *") public void sendTotal() throws Exception { log.info(baseConfig.getLine().getPort() + "发送总召"); SendDataFrameHelper.sendTotalSummonFrame(OnlineDataMain.master.getFuture().channel(), baseConfig.getLine().getCoa(), 6, OnlineDataMain.master.getLog()); } @SneakyThrows @Scheduled(cron = "0 0/10 * * * *") public void saveToFile() { List> datas = CommonData.getListAndClean(); if (!datas.isEmpty()) { String timestamp = sdf.format(System.currentTimeMillis()); String filePath = baseConfig.getSaveDir() + timestamp + ".csv"; File folder = new File(baseConfig.getSaveDir()); if (!folder.exists()) { folder.mkdirs(); // 使用mkdirs()可以创建多级目录 } try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(filePath))) { datas.forEach(map -> { try { writer.write( map.values().stream() .map(Object::toString) .collect(Collectors.joining(",")) ); writer.newLine(); } catch (IOException e) { throw new RuntimeException(e); } }); } } } @Scheduled(cron = "0 0/2 * * * *") public void printMapCoount() { log.info(baseConfig.getLine().getPort() + ",当前数据大小:" + CommonData.map.size()); } }