zhaowenxuan
2025-03-13 9a7ee34013ff0a0eb9a65d76ced42b4f13f3e4d4
ltkj-admin/src/main/java/com/ltkj/web/config/timer/DefaultScheduled.java
@@ -1,7 +1,12 @@
package com.ltkj.web.config.timer;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ltkj.common.enums.DataSourceType;
import com.ltkj.db.DataSourceConfig;
import com.ltkj.db.DataSourceContextHolder;
import com.ltkj.framework.datasource.DynamicDataSourceContextHolder;
import com.ltkj.hosp.domain.DictHosp;
import com.ltkj.hosp.domain.TjJcycxm;
import com.ltkj.hosp.mapper.TestMapper;
import com.ltkj.hosp.service.*;
@@ -16,16 +21,12 @@
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalTime;
import java.time.ZonedDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.locks.ReentrantLock;
/**
@@ -34,8 +35,8 @@
 * @Date: 2024/7/25 15:05
 */
@Slf4j
@Component
@Profile("!dev & !prod & !test")
//@Component
//@Profile("!prod & !test")
public class DefaultScheduled {
@@ -59,36 +60,100 @@
    private TjJcycxmService jcycxmService;
    @Autowired
    private AwsService awsService;
    @Resource
    private IDictHospService dictHospService;
    @Autowired
    private DataSourceConfig dataSourceConfig;
    private final ReentrantLock reentrantLock = new ReentrantLock();
    private  Set<String> set=new HashSet();
    private ScheduledExecutorService scheduledExecutorService;
    private ScheduledExecutorService addscheduledExecutorService;
    private ScheduledFuture<?> scheduledFuture;
    private ScheduledFuture<?> addscheduledFuture;
    private static final SimpleDateFormat dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @PostConstruct
    private void init() {
        scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        scheduleNextTask(0); // 初次启动立即执行
        List<DictHosp> hospList = dictHospService.list();
        if(null !=hospList && !hospList.isEmpty()){
            for (DictHosp hosp : hospList) {
                String code = hosp.getCode();
                if(StringUtil.isNotBlank(code)){
                    set.add(code);
                    String dbName = hosp.getDbname();
                    scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
                    scheduleNextTask(0,dbName,hosp.getCode()); // 初次启动立即执行
                }
            }
        }
        schedulePeriodicTaskCheck(0);
    }
    private void scheduleNextTask(long delayInMinutes) {
    private void scheduleNextTask(long delayInMinutes,String dbName,String yqbm) {
        if (scheduledFuture != null) {
            scheduledFuture.cancel(false);
        }
        Date nextExecutionTime = new Date(System.currentTimeMillis() + TimeUnit.MINUTES.toMillis(delayInMinutes));
        log.info("下次执行任务时间 -> {}", dateTimeFormat.format(nextExecutionTime));
        log.info("任务下次执行任务时间 -> {}", dateTimeFormat.format(nextExecutionTime));
        scheduledFuture = scheduledExecutorService.schedule(this::exec, delayInMinutes, TimeUnit.MINUTES);
        scheduledFuture = scheduledExecutorService.schedule(() -> exec(dbName,yqbm), delayInMinutes, TimeUnit.MINUTES);
    }
    private void exec() {
    // 定时检查是否有新的用户需要添加任务
    private void schedulePeriodicTaskCheck(long delayInMinutes) {
        //切主库
        dataSourceConfig.addDataSource(DataSourceType.MASTER.name());
        DataSourceContextHolder.setDataSourceKey(DataSourceType.MASTER.name());
        if (addscheduledFuture != null) {
            addscheduledFuture.cancel(false);
        }
        Date nextExecutionTime = new Date(System.currentTimeMillis() + TimeUnit.MINUTES.toMillis(delayInMinutes));
        log.info("添加线程池定时下次执行任务时间 -> {}", dateTimeFormat.format(nextExecutionTime));
        addscheduledFuture = addscheduledExecutorService.schedule(this::checkAndAddNewTasks, delayInMinutes, TimeUnit.MINUTES);
        checkAndAddNewTasks();
    }
    // 检查并添加新的用户任务
    public void checkAndAddNewTasks() {
        String dsrwsjjg = configService.selectConfigByKey("dsrwsjjg");
        List<DictHosp> hospList = dictHospService.list();
        if(null !=hospList && !hospList.isEmpty()){
            for (DictHosp hosp : hospList) {
                if(null !=hosp && StringUtil.isNotBlank(hosp.getCode()) && !set.contains(hosp.getCode())){
                    set.add(hosp.getCode());
                    String dbName = hosp.getDbname();
                    scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
                    scheduleNextTask(0,dbName,hosp.getCode()); // 初次启动立即执行
                }
            }
        }
        // 动态获取下次任务的间隔
        int minute = Integer.parseInt(dsrwsjjg);
        if (minute < 5) minute = 5;
        if (minute > 59) minute = 59;
        schedulePeriodicTaskCheck(minute);
    }
    private void exec(String dbName,String yqbm) {
        //切库
        dataSourceConfig.addDataSource(dbName);
        DataSourceContextHolder.setDataSourceKey(dbName);
        String dsqkssj = configService.selectConfigByKey("dsqkssj");
        String dsqjssj = configService.selectConfigByKey("dsqjssj");
        String yqbm = configService.selectConfigByKey("common_api_service_hospbm");
        boolean panduandangqianshijian = panduandangqianshijian(dsqkssj, dsqjssj);
        log.info("定时器自动同步检验检查结果");
        log.info("当前时间是否在 " + dsqkssj + " 点到 " + dsqjssj + " 点之间: " + panduandangqianshijian);
@@ -109,7 +174,7 @@
                        if (null != jy && !jy.isEmpty()) {
                            log.info("同步检验人员 执行数量->{}", jy.size());
                            for (String s : jy) {
                                extractedjianyan(s);
                                extractedjianyan(s,yqbm);
                            }
                        }
@@ -117,7 +182,7 @@
                        if (null != jc && !jc.isEmpty()) {
                            log.info("同步检查人员 执行数量->{}", jc.size());
                            for (String s : jc) {
                                extractedjiancha(s);
                                extractedjiancha(s,yqbm);
                            }
                        }
                        Map<String, Object> map = new HashMap<>();
@@ -161,25 +226,23 @@
                            int minute = Integer.parseInt(dsrwsjjg);
                            if (minute < 5) minute = 5;
                            if (minute > 59) minute = 59;
                            scheduleNextTask(minute);
                            scheduleNextTask(minute,dbName,yqbm);
                        }else {
                            log.info("执行存储过程出参失败");
                            scheduleNextTask(Long.parseLong(dsrwsjjg));
                            scheduleNextTask(Long.parseLong(dsrwsjjg),dbName,yqbm);
                        }
                    }
                }else {
                    log.info("不在定时器执行时间范围之内!!!");
                    scheduleNextTask(Long.parseLong(dsrwsjjg));
                    scheduleNextTask(Long.parseLong(dsrwsjjg),dbName,yqbm);
                }
            } catch (Exception e) {
                scheduleNextTask(Long.parseLong(dsrwsjjg));
                scheduleNextTask(Long.parseLong(dsrwsjjg),dbName,yqbm);
                log.error("定时器执行报错");
                log.error(String.valueOf(e));
//                e.printStackTrace();
            } finally {
                reentrantLock.unlock();
            }
    }
    private boolean panduandangqianshijian(String kssj, String jssj) {
@@ -188,7 +251,7 @@
        return time.isAfter(LocalTime.of(Integer.parseInt(kssj), 0)) && time.isBefore(LocalTime.of(Integer.parseInt(jssj), 0));
    }
    private void extractedjianyan(String s) {
    private void extractedjianyan(String s,String yqbm) {
        try {
            List<Aws> awsList = testMapper.getWsxmLtkjHysqdByLisViBySLAVEWS(s);
            if(null !=awsList && !awsList.isEmpty()){
@@ -198,7 +261,7 @@
                awsService.saveBatch(awsList);
                log.info("保存外送项目成功");
            }
            List<LtkjHysqd> hysqdList = testMapper.getCcXZxYyLtkjHysqdByLisVi(s);
            List<LtkjHysqd> hysqdList = testMapper.getCcXZxYyLtkjHysqdByLisVi(s,yqbm);
            List<LtkjHysqd> wssq = testMapper.getWsxmLtkjHysqdByLisVi(s);
            if(null !=wssq && !wssq.isEmpty())hysqdList.addAll(wssq);
            if (null != hysqdList && !hysqdList.isEmpty()) {
@@ -226,16 +289,16 @@
    }
    private void extractedjiancha(String s) {
    private void extractedjiancha(String s,String yqbm) {
        try {
            List<LtkjExamJcsqd> jcsqdList = testMapper.getCcXZxYyPacsLtkjExamJcsqd(s);
            List<LtkjExamJcsqd> jcsqdList = testMapper.getCcXZxYyPacsLtkjExamJcsqd(s,yqbm);
            if (null != jcsqdList && !jcsqdList.isEmpty()) {
                DynamicDataSourceContextHolder.clearDataSourceType();
                jcsqdService.deletedLtkjJcsqdByTjhAndTmh(s);
                jcbgdService.deletedLtkjJcbgdByTjhAndTmh(s);
                jcsqdService.saveBatch(jcsqdList);
                List<LtkjExamJcbgd> jcbgdList = testMapper.getCcXZxYyPacsLtkjExamJcbgd(s);
                List<LtkjExamJcbgd> jcbgdList = testMapper.getCcXZxYyPacsLtkjExamJcbgd(s,yqbm);
                DynamicDataSourceContextHolder.clearDataSourceType();
                if (null != jcbgdList && !jcbgdList.isEmpty()) jcbgdService.saveBatch(jcbgdList);
                DynamicDataSourceContextHolder.clearDataSourceType();