# SvaJobWorker.java

    package cloud.wconnect.workperformance.scheduler.sva;

    import cloud.wconnect.commonlib.cons.FunctionIdConstant;
    import cloud.wconnect.commonlib.cons.SchedulerCons;
    import cloud.wconnect.commonlib.service.CommonService;
    import cloud.wconnect.commonlib.service.MailInternalService;
    import cloud.wconnect.commonlib.util.RateLimitUtils;
    import cloud.wconnect.workperformance.businesstask.sva.actualscheduledhours.SvaActualHoursTask;
    import cloud.wconnect.workperformance.businesstask.sva.actualscheduledhours.SvaScheduleHoursTask;
    import cloud.wconnect.workperformance.businesstask.sva.employee.SvaEmployeesTask;
    import cloud.wconnect.workperformance.businesstask.sva.operatingstatisticsdaily.SvaOperatingStatisticsDailyTask;
    import cloud.wconnect.workperformance.businesstask.sva.saleforecast.SvaSaleForecastTask;
    import cloud.wconnect.workperformance.cons.sva.SvaNotifyTypeEnum;
    import cloud.wconnect.workperformance.entity.sva.SvaScheduler;
    import cloud.wconnect.workperformance.service.AmazonSqsService;
    import cloud.wconnect.workperformance.service.sva.scheduleactual.ISvaSchedulerService;
    import com.alibaba.fastjson.JSONObject;
    import jakarta.annotation.Resource;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.commons.collections.CollectionUtils;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.scheduling.annotation.Scheduled;
    import org.springframework.stereotype.Component;
    import software.amazon.awssdk.services.sqs.model.Message;

    import java.text.MessageFormat;
    import java.util.List;
    import java.util.Objects;

    @Slf4j
    @Component
    public class SvaJobWorker {
        @Resource
        private AmazonSqsService amazonSqsService;
        @Resource
        private ISvaSchedulerService schedulerService;
        @Resource
        private MailInternalService mailInternalService;
        @Resource
        private SvaActualHoursTask svaActualHoursTask;
        @Resource
        private SvaScheduleHoursTask svaScheduleHoursTask;
        @Resource
        private SvaEmployeesTask svaEmployeesTask;
        @Resource
        private SvaOperatingStatisticsDailyTask operatingStatisticsDailyTask;
        @Resource
        private SvaSaleForecastTask svaSaleForecastTask;
        @Resource
        private CommonService commonService;

        @Value("${sqs.queue-url.sva_scheduler}")
        private String schedulerUrl;

        /**
         * 消费消息
         *
         * @author zc
         * @date 2024/3/13
         */
        @Scheduled(cron = "${schedule.cron.run-scheduler-job}", zone = "${default.timezone}")
        public void run() {
            List<Message> messages = amazonSqsService.getMessagesBatch(schedulerUrl);
            if (CollectionUtils.isNotEmpty(messages)) {
                for (Message message : messages) {
                    // message为json字符串：{"jobId": "894bd865a742c84d9a74c190b1e3cb92"}, 该jobId 为 sva_scheduler 表的 id，该对应记录保存着任务的详细信息
                    // 警告: 执行任务的具体方法应该使用新的线程，而不是在本线程执行（要确保本线程不会被阻塞或异常退出）

                    SvaScheduler schedulerJob = null;
                    try {
                        JSONObject jsonObject = JSONObject.parseObject(message.body());
                        String jobId = (String) jsonObject.get(SchedulerCons.JOB_ID);
                        schedulerJob = schedulerService.getById(jobId);

                        if (Objects.nonNull(schedulerJob)) {
                            if (!commonService.checkPropertyEffectiveAndOpenFunction(schedulerJob.getPropertyId(), FunctionIdConstant.SCHEDULE_VS_ACTUAL)) {
                                return;
                            }

                            // 获取分类
                            int category = schedulerJob.getCategory();
                            if (category == SvaNotifyTypeEnum.MISSING_REPORT_EMPLOYEE.getType()) {
                                svaEmployeesTask.reportMissingCheck(schedulerJob);
                            } else if (category == SvaNotifyTypeEnum.MISSING_REPORT_AV_ACTUAL.getType()) {
                                svaActualHoursTask.reportMissingCheck(schedulerJob);
                            } else if (category == SvaNotifyTypeEnum.MISSING_REPORT_OPERATING.getType()) {
                                operatingStatisticsDailyTask.dataMissingCheck(schedulerJob);
                            } else if (category == SvaNotifyTypeEnum.MISSING_DATA_SALES_FORECAST.getType()) {
                                svaSaleForecastTask.dataMissingCheck(schedulerJob);
                            } else if (category == SvaNotifyTypeEnum.MISSING_REPORT_AV_SCHEDULE.getType()) {
                                svaScheduleHoursTask.reportMissingCheck(schedulerJob);
                            }

                            // 任务执行次数加1
                            schedulerService.plusRunTimes(jobId);
                        }
                    } catch (Exception e) {
                        log.error("SQS consume error[SvaJobWorker] - Message: {}; Exception: {}", message.body(), e.getMessage());
                        if (RateLimitUtils.tryAcquire(this)) {
                            sendAlertEmail(schedulerUrl, message.body(), schedulerJob, e.getMessage());
                        }
                    } finally {
                        // 删除消息
                        amazonSqsService.deleteMessage(schedulerUrl, message.receiptHandle());
                    }
                }
                run();
            }
        }

        /**
         * 发送alertEmail
         *
         * @param schedulerUrl 定时任务调度URL
         * @param message      消息
         * @param schedulerJob 定时任务对象
         * @param exception    异常信息
         * @author zc
         * @date 2024/3/13
         */
        public void sendAlertEmail(String schedulerUrl, String message, SvaScheduler schedulerJob, String exception) {
            String subject = "[Warning] - process SvaJobWorker";
            String mailContent = MessageFormat.format("SQS url:{0}<br/>Message:{1}<br/>SchedulerJob:{2}<br/>Exception:{3}",
                    schedulerUrl, message, Objects.nonNull(schedulerJob) ? schedulerJob.toString() : "", exception);
            mailInternalService.sendAlertEmail(subject, mailContent);
        }
    }