You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

61 lines
2.0KB

  1. package com.example.webapi.service;
  2. import lombok.RequiredArgsConstructor;
  3. import lombok.extern.slf4j.Slf4j;
  4. import org.slf4j.Logger;
  5. import org.slf4j.LoggerFactory;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.boot.CommandLineRunner;
  8. import org.springframework.scheduling.annotation.Scheduled;
  9. import org.springframework.stereotype.Component;
  10. import org.springframework.stereotype.Service;
  11. @Component
  12. @Slf4j
  13. @RequiredArgsConstructor
  14. public class ScheduledSyncService implements CommandLineRunner {
  15. private static final Logger logger = LoggerFactory.getLogger(ScheduledSyncService.class);
  16. @Autowired
  17. private DataSyncService dataSyncService;
  18. /**
  19. * 每5分钟执行一次增量同步
  20. */
  21. @Scheduled(fixedRate = 300000) // 5分钟 = 300000毫秒
  22. public void syncIncrementalData() {
  23. try {
  24. logger.info("开始定时增量同步数据...");
  25. int count = dataSyncService.syncIncrementalData();
  26. logger.info("定时增量同步完成,成功同步 {} 条记录", count);
  27. } catch (Exception e) {
  28. logger.error("定时增量同步过程中发生错误: {}", e.getMessage(), e);
  29. }
  30. }
  31. /**
  32. * 每天凌晨2点执行全量同步检查
  33. */
  34. @Scheduled(cron = "0 0 2 * * ?")
  35. public void dailyFullSync() {
  36. try {
  37. logger.info("开始每日全量同步检查...");
  38. int count = dataSyncService.syncIncrementalData();
  39. logger.info("每日全量同步检查完成,成功同步 {} 条记录", count);
  40. } catch (Exception e) {
  41. logger.error("每日全量同步检查过程中发生错误: {}", e.getMessage(), e);
  42. }
  43. }
  44. @Override
  45. public void run(String... args) throws Exception {
  46. System.out.println("项目启动后执行增量同步------------------");
  47. try {
  48. syncIncrementalData();
  49. } catch (Exception e) {
  50. logger.error("启动时增量同步失败: {}", e.getMessage(), e);
  51. }
  52. }
  53. }