package com.simuwang.manage.init; import com.alibaba.fastjson.JSON; import com.simuwang.base.common.enums.OpenStatusType; import com.simuwang.base.common.util.QuartzUtils; import com.simuwang.base.config.DaqProperties; import com.simuwang.base.pojo.dos.MailboxInfoDO; import com.simuwang.base.pojo.dto.MailboxInfoDTO; import com.simuwang.base.pojo.dto.QuartzBean; import com.simuwang.manage.service.EmailConfigService; import org.quartz.Scheduler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.context.annotation.Configuration; import org.springframework.core.annotation.Order; import java.util.List; /** * 定时任务启动类 * Author: chenjianhua * Date: 2024/9/17 11:55 * Description: ${DESCRIPTION} */ @Configuration @Order(2) public class QuartzConfig implements ApplicationRunner { @Autowired private Scheduler scheduler; private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired private EmailConfigService emailConfigService; @Value("${spring.application.name}") private String groupName; private String JOB_CLASS="com.simuwang.manage.task.ParseSchedulerTask"; private final Boolean enableQuartz; public QuartzConfig(DaqProperties properties) { this.enableQuartz = properties.getEnableQuartz(); } @Override public void run(ApplicationArguments args){ // 没有开启定时任务功能时直接退出 if (!enableQuartz) { return; } List mailboxInfoDOS = emailConfigService.getAll(); for(MailboxInfoDO mailboxInfoDO : mailboxInfoDOS){ try{ QuartzBean quartzBean = new QuartzBean(); quartzBean.setCronExpression(mailboxInfoDO.getCron()); quartzBean.setStatus(mailboxInfoDO.getOpenStatus()); quartzBean.setGroupName(groupName); quartzBean.setJobName(mailboxInfoDO.getEmail()); quartzBean.setJobClass(JOB_CLASS); //请求参数 MailboxInfoDTO paramDTO = new MailboxInfoDTO(); paramDTO.setAccount(mailboxInfoDO.getEmail()); paramDTO.setPassword(mailboxInfoDO.getPassword()); paramDTO.setPort(mailboxInfoDO.getPort()); paramDTO.setHost(mailboxInfoDO.getServer()); paramDTO.setProtocol(mailboxInfoDO.getProtocol()); quartzBean.setJobParam(JSON.toJSONString(paramDTO)); QuartzUtils.createScheduleJob(scheduler,quartzBean); if(mailboxInfoDO.getOpenStatus().equals(OpenStatusType.YES.getCode())){ QuartzUtils.resumeScheduleJob(scheduler,quartzBean.getJobName()); }else{ QuartzUtils.pauseScheduleJob(scheduler,quartzBean.getJobName()); } }catch (Exception e) { logger.error(e.getMessage(),e); } } } }