云
10 小时以前 02a1ae81eba7b48223052fb833859f0a65dd7d21
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
package cn.iocoder.yudao.module.mes.job.pro;
 
import cn.iocoder.yudao.module.mes.service.pro.bagcode.MesProBagCodeGenerateTaskService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
 
/**
 * 袋码生成任务清理
 * <p>
 * 进程重启后内存运行态丢失,表中停在「排队中/生成中/取消中」的记录不会再有线程推进,
 * 由本任务回收为失败并清理其半成品数据。用 Spring 自带的 {@code @Scheduled} 而非 Quartz JobHandler:
 * 后者需要在管理后台手工登记,漏登记就会静默不执行,这里的清理属于必须开箱即跑的兜底逻辑。
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class MesProBagCodeGenerateCleanupTask {
 
    private final MesProBagCodeGenerateTaskService taskService;
 
    /**
     * 每 5 分钟回收一次异常中断的任务
     */
    @Scheduled(cron = "0 */5 * * * ?")
    public void cleanup() {
        try {
            int tasks = taskService.recycleStaleTasks();
            if (tasks > 0) {
                log.info("[cleanup][回收残留袋码生成任务 {} 个]", tasks);
            }
        } catch (Exception e) {
            log.error("[cleanup][回收残留袋码生成任务失败]", e);
        }
    }
 
    /**
     * 启动时立刻回收一次,避免残留任务以「生成中」状态一直挂在界面上
     */
    @EventListener(ApplicationReadyEvent.class)
    public void recycleOnStartup() {
        try {
            int tasks = taskService.recycleStaleTasks();
            if (tasks > 0) {
                log.info("[recycleOnStartup][启动回收残留袋码生成任务 {} 个]", tasks);
            }
        } catch (Exception e) {
            log.error("[recycleOnStartup][启动回收袋码生成任务失败]", e);
        }
    }
 
}