gongchunyi
5 天以前 cecd7580b5e629173bdb5b258f2676d16d580f72
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
package com.ruoyi.safe.service.impl;
 
import com.ruoyi.safe.pojo.SafeFacilityInspectionTask;
import lombok.RequiredArgsConstructor;
import org.quartz.CronScheduleBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.springframework.stereotype.Service;
 
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeParseException;
import java.util.Arrays;
import java.util.Date;
import java.util.stream.Collectors;
 
@Service
@RequiredArgsConstructor
public class SafeFacilityInspectionTaskScheduler {
 
    private static final String JOB_GROUP = "safeFacilityInspectionTask";
    private static final String TRIGGER_GROUP = "safeFacilityInspectionTaskTrigger";
 
    private final Scheduler scheduler;
 
    public void scheduleTask(SafeFacilityInspectionTask task) throws SchedulerException {
        JobDetail jobDetail = buildJobDetail(task);
        if (scheduler.checkExists(jobDetail.getKey())) {
            scheduler.deleteJob(jobDetail.getKey());
        }
        scheduler.scheduleJob(jobDetail, buildJobTrigger(task, jobDetail));
    }
 
    public void rescheduleTask(SafeFacilityInspectionTask task) throws SchedulerException {
        TriggerKey triggerKey = getTriggerKey(task.getId());
        Trigger oldTrigger = scheduler.getTrigger(triggerKey);
        if (oldTrigger == null) {
            scheduleTask(task);
            return;
        }
        JobDetail jobDetail = scheduler.getJobDetail(oldTrigger.getJobKey());
        if (jobDetail == null) {
            scheduleTask(task);
            return;
        }
        scheduler.rescheduleJob(triggerKey, buildJobTrigger(task, jobDetail));
    }
 
    public void unscheduleTask(Long taskId) {
        try {
            scheduler.deleteJob(getJobKey(taskId));
        } catch (SchedulerException e) {
            throw new RuntimeException(e);
        }
    }
 
    private JobDetail buildJobDetail(SafeFacilityInspectionTask task) {
        JobDataMap jobDataMap = new JobDataMap();
        jobDataMap.put("taskId", task.getId());
        jobDataMap.put("taskName", task.getInspectionName());
        jobDataMap.put("frequencyType", task.getFrequencyType());
 
        return JobBuilder.newJob(SafeFacilityInspectionTaskJob.class)
                .withIdentity(getJobKey(task.getId()))
                .withDescription(task.getInspectionName())
                .usingJobData(jobDataMap)
                .storeDurably(true)
                .requestRecovery(true)
                .build();
    }
 
    private Trigger buildJobTrigger(SafeFacilityInspectionTask task, JobDetail jobDetail) {
        return TriggerBuilder.newTrigger()
                .withIdentity(getTriggerKey(task.getId()))
                .withDescription(task.getInspectionName() + "_TRIGGER")
                .forJob(jobDetail)
                .withSchedule(CronScheduleBuilder
                        .cronSchedule(convertToCronExpression(task))
                        .withMisfireHandlingInstructionDoNothing())
                .startAt(task.getNextExecutionTime() != null
                        ? Date.from(task.getNextExecutionTime().atZone(ZoneId.systemDefault()).toInstant())
                        : new Date())
                .build();
    }
 
    private JobKey getJobKey(Long taskId) {
        return new JobKey("safeFacilityInspectionTask_" + taskId, JOB_GROUP);
    }
 
    private TriggerKey getTriggerKey(Long taskId) {
        return new TriggerKey("safeFacilityInspectionTaskTrigger_" + taskId, TRIGGER_GROUP);
    }
 
    private String convertToCronExpression(SafeFacilityInspectionTask task) {
        if (task == null || task.getFrequencyType() == null || task.getFrequencyDetail() == null) {
            throw new IllegalArgumentException("任务频率不能为空");
        }
        return switch (task.getFrequencyType().toUpperCase()) {
            case "DAILY" -> convertDailyToCron(task.getFrequencyDetail());
            case "WEEKLY" -> convertWeeklyToCron(task.getFrequencyDetail());
            case "MONTHLY" -> convertMonthlyToCron(task.getFrequencyDetail());
            default -> throw new IllegalArgumentException("不支持的频率类型: " + task.getFrequencyType());
        };
    }
 
    private String convertDailyToCron(String frequencyDetail) {
        LocalTime time = parseTime(frequencyDetail);
        return String.format("0 %d %d * * ?", time.getMinute(), time.getHour());
    }
 
    private String convertWeeklyToCron(String frequencyDetail) {
        String[] parts = validateAndSplit(frequencyDetail, 2);
        String daysOfWeek = Arrays.stream(parts[0].split("\\|"))
                .map(this::convertSingleDayName)
                .collect(Collectors.joining(","));
        LocalTime time = parseTime(parts[1]);
        return String.format("0 %d %d ? * %s", time.getMinute(), time.getHour(), daysOfWeek);
    }
 
    private String convertMonthlyToCron(String frequencyDetail) {
        String[] parts = validateAndSplit(frequencyDetail, 2);
        int day = validateDayOfMonth(parts[0]);
        LocalTime time = parseTime(parts[1]);
        return String.format("0 %d %d %d * ?", time.getMinute(), time.getHour(), day);
    }
 
    private String[] validateAndSplit(String input, int expectedParts) {
        String[] parts = input.split(",");
        if (parts.length != expectedParts) {
            throw new IllegalArgumentException("任务频率详情格式错误");
        }
        return Arrays.stream(parts).map(String::trim).toArray(String[]::new);
    }
 
    private LocalTime parseTime(String timeStr) {
        try {
            return LocalTime.parse(timeStr);
        } catch (DateTimeParseException e) {
            throw new IllegalArgumentException("时间格式必须为HH:mm", e);
        }
    }
 
    private int validateDayOfMonth(String dayStr) {
        int day = Integer.parseInt(dayStr);
        if (day < 1 || day > 31) {
            throw new IllegalArgumentException("日期必须在1-31之间");
        }
        return day;
    }
 
    private String convertSingleDayName(String dayName) {
        return switch (dayName.toUpperCase()) {
            case "MON" -> "MON";
            case "TUE" -> "TUE";
            case "WED" -> "WED";
            case "THU" -> "THU";
            case "FRI" -> "FRI";
            case "SAT" -> "SAT";
            case "SUN" -> "SUN";
            default -> throw new IllegalArgumentException("无效的星期几: " + dayName);
        };
    }
}