# ItRequestTask.java

    package cloud.wconnect.it.businesstask.itrequest;

    import cloud.wconnect.commonlib.cons.BaseConstant;
    import cloud.wconnect.commonlib.service.MailInternalService;
    import cloud.wconnect.it.service.itrequest.IItticketService;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.scheduling.annotation.Scheduled;
    import org.springframework.stereotype.Component;

    import java.time.LocalDateTime;
    import java.time.format.DateTimeFormatter;
    import java.util.concurrent.TimeUnit;

    /**
     * @author: yyt
     * 2024-04-16
     */
    @Slf4j
    @Component
    public class ItRequestTask {

        @Autowired
        private RedisTemplate<String, Object> redisTemplate;
        @Autowired
        private MailInternalService mailInternalService;
        @Autowired
        private IItticketService itticketService;

        private static final String PREFIX_KEY = "wconnect:task:it-request-auto-closed:";

        /**
         * 每天自动关闭超过7天未关闭的数据
         *
         * @author yyt
         * @date 2024/4/16
         **/
        @Scheduled(cron = "${schedule.cron.notify.it-request-auto-closed}", zone = "${default.timezone}")
        public void autoClosedData() {
            log.info("autoClosedItRequestData... start");
            String alertTitle = "[Warning] - Exceptions About Auto Closed It Request Data";
            StringBuilder warningEmail = new StringBuilder("<p>There is something wrong when auto closed it request data.</p>");

            try {
                // 处理并发
                String currentDate = LocalDateTime.now().format(DateTimeFormatter.ofPattern(BaseConstant.DATE_FORMAT_YYMMDDHH));
                if (!preventConcurrency(PREFIX_KEY + currentDate)) {
                    log.warn("autoClosedItRequestData... date:{}. other machines have already executed", currentDate);
                    log.info("autoClosedItRequestData... end");
                    return;
                }

                itticketService.autoClose();
            } catch (Exception e) {
                log.warn("autoClosedItRequestData...  exception occurs:", e);
                warningEmail.append("<p>Exception:").append(e).append("</p>");
                mailInternalService.sendAlertEmail(alertTitle, warningEmail.toString());
            }

            log.info("autoClosedItRequestData... end");
        }

        /**
         * 防止并发
         *
         * @param key 唯一标识
         * @return 锁成功
         * @author yyt
         * @date 2024/4/16
         */
        private Boolean preventConcurrency(String key) {
            return redisTemplate.opsForValue().setIfAbsent(key, 0, 1, TimeUnit.DAYS);
        }

    }