TimeSaveScheduled.java 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package com.energy.online.data.crontab;
  2. import com.energy.online.data.OnlineDataMain;
  3. import com.energy.online.data.common.CommonData;
  4. import com.energy.online.data.dto.BaseConfig;
  5. import lombok.SneakyThrows;
  6. import lombok.extern.slf4j.Slf4j;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.scheduling.annotation.Scheduled;
  9. import org.springframework.stereotype.Component;
  10. import wei.yigulu.iec104.util.SendDataFrameHelper;
  11. import java.io.BufferedWriter;
  12. import java.io.File;
  13. import java.io.IOException;
  14. import java.nio.file.Files;
  15. import java.nio.file.Paths;
  16. import java.text.SimpleDateFormat;
  17. import java.util.List;
  18. import java.util.Map;
  19. import java.util.stream.Collectors;
  20. @Component
  21. @Slf4j
  22. public class TimeSaveScheduled {
  23. private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
  24. @Autowired
  25. private BaseConfig baseConfig;
  26. // @Scheduled(cron = "0/1 * * * * *")
  27. @Scheduled(cron = "${my.scheduled.cron}")
  28. public void collectData() {
  29. CommonData.addList();
  30. }
  31. @Scheduled(cron = "0 0/2 * * * *")
  32. public void sendTotal() throws Exception {
  33. log.info(baseConfig.getLine().getPort() + "发送总召");
  34. SendDataFrameHelper.sendTotalSummonFrame(OnlineDataMain.master.getFuture().channel(), baseConfig.getLine().getCoa(), 6, OnlineDataMain.master.getLog());
  35. }
  36. @SneakyThrows
  37. @Scheduled(cron = "0 0/10 * * * *")
  38. public void saveToFile() {
  39. List<Map<Integer, Object>> datas = CommonData.getListAndClean();
  40. if (!datas.isEmpty()) {
  41. String timestamp = sdf.format(System.currentTimeMillis());
  42. String filePath = baseConfig.getSaveDir() + timestamp + ".csv";
  43. File folder = new File(baseConfig.getSaveDir());
  44. if (!folder.exists()) {
  45. folder.mkdirs(); // 使用mkdirs()可以创建多级目录
  46. }
  47. try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(filePath))) {
  48. datas.forEach(map -> {
  49. try {
  50. writer.write(
  51. map.values().stream()
  52. .map(Object::toString)
  53. .collect(Collectors.joining(","))
  54. );
  55. writer.newLine();
  56. } catch (IOException e) {
  57. throw new RuntimeException(e);
  58. }
  59. });
  60. }
  61. }
  62. }
  63. @Scheduled(cron = "0 0/2 * * * *")
  64. public void printMapCoount() {
  65. log.info(baseConfig.getLine().getPort() + ",当前数据大小:" + CommonData.map.size());
  66. }
  67. }