xuefei
2020-12-10 eeeb7233935ea9b10e99043bdbf740ef86c9bf20
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
package cn.cetc54.platform.quartz.controller;
 
import cn.cetc54.platform.core.common.constant.CommonConstant;
import cn.cetc54.platform.core.common.exception.PlatformException;
import cn.cetc54.platform.core.common.utils.PageUtil;
import cn.cetc54.platform.core.common.utils.ResultUtil;
import cn.cetc54.platform.core.common.vo.PageVo;
import cn.cetc54.platform.core.common.vo.Result;
import cn.cetc54.platform.quartz.entity.QuartzJob;
import cn.cetc54.platform.quartz.service.QuartzJobService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
 
import java.util.List;
 
/**
 * @author Exrick
 */
@Slf4j
@RestController
@Api(description = "定时任务管理接口")
@RequestMapping("/platform/quartzJob")
@Transactional
public class QuartzJobController {
 
    @Autowired
    private QuartzJobService quartzJobService;
 
    @Autowired
    private Scheduler scheduler;
 
    @RequestMapping(value = "/getAllByPage", method = RequestMethod.GET)
    @ApiOperation(value = "获取所有定时任务")
    public Result<Page<QuartzJob>> getAll(PageVo page){
 
        Page<QuartzJob> data = quartzJobService.findAll(PageUtil.initPage(page));
        return new ResultUtil<Page<QuartzJob>>().setData(data);
    }
 
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ApiOperation(value = "添加定时任务")
    public Result<Object> addJob(QuartzJob job){
 
        List<QuartzJob> list = quartzJobService.findByJobClassName(job.getJobClassName());
        if(list!=null&&list.size()>0){
            return ResultUtil.error("该定时任务类名已存在");
        }
        add(job.getJobClassName(),job.getCronExpression(),job.getParameter());
        quartzJobService.save(job);
        return ResultUtil.success("创建定时任务成功");
    }
 
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    @ApiOperation(value = "更新定时任务")
    public Result<Object> editJob(QuartzJob job){
 
        delete(job.getJobClassName());
        add(job.getJobClassName(),job.getCronExpression(),job.getParameter());
        job.setStatus(CommonConstant.STATUS_NORMAL);
        quartzJobService.update(job);
        return ResultUtil.success("更新定时任务成功");
    }
 
    @RequestMapping(value = "/pause", method = RequestMethod.POST)
    @ApiOperation(value = "暂停定时任务")
    public Result<Object> pauseJob(QuartzJob job){
 
        try {
            scheduler.pauseJob(JobKey.jobKey(job.getJobClassName()));
        } catch (SchedulerException e) {
            throw new PlatformException("暂停定时任务失败");
        }
        job.setStatus(CommonConstant.STATUS_DISABLE);
        quartzJobService.update(job);
        return ResultUtil.success("暂停定时任务成功");
    }
 
    @RequestMapping(value = "/resume", method = RequestMethod.POST)
    @ApiOperation(value = "恢复定时任务")
    public Result<Object> resumeJob(QuartzJob job){
 
        try {
            scheduler.resumeJob(JobKey.jobKey(job.getJobClassName()));
        } catch (SchedulerException e) {
            throw new PlatformException("恢复定时任务失败");
        }
        job.setStatus(CommonConstant.STATUS_NORMAL);
        quartzJobService.update(job);
        return ResultUtil.success("恢复定时任务成功");
    }
 
    @RequestMapping(value = "/delByIds", method = RequestMethod.POST)
    @ApiOperation(value = "删除定时任务")
    public Result<Object> deleteJob(@RequestParam String[] ids){
 
        for(String id:ids){
            QuartzJob job = quartzJobService.get(id);
            delete(job.getJobClassName());
            quartzJobService.delete(job);
        }
        return ResultUtil.success("删除定时任务成功");
    }
 
    /**
     * 添加定时任务
     * @param jobClassName
     * @param cronExpression
     * @param parameter
     */
    public void add(String jobClassName, String cronExpression, String parameter){
 
        try {
            // 启动调度器
            scheduler.start();
 
            //构建job信息
            JobDetail jobDetail = JobBuilder.newJob(getClass(jobClassName).getClass())
                    .withIdentity(jobClassName)
                    .usingJobData("parameter", parameter)
                    .build();
 
            //表达式调度构建器(即任务执行的时间) 使用withMisfireHandlingInstructionDoNothing() 忽略掉调度暂停过程中没有执行的调度
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cronExpression).withMisfireHandlingInstructionDoNothing();
 
            //按新的cronExpression表达式构建一个新的trigger
            CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(jobClassName)
                    .withSchedule(scheduleBuilder).build();
 
            scheduler.scheduleJob(jobDetail, trigger);
        } catch (SchedulerException e) {
            log.error(e.toString());
            throw new PlatformException("创建定时任务失败");
        } catch (java.lang.Exception e){
            throw new PlatformException("后台找不到该类名任务");
        }
    }
 
    /**
     * 删除定时任务
     * @param jobClassName
     */
    public void delete(String jobClassName){
 
        try {
            scheduler.pauseTrigger(TriggerKey.triggerKey(jobClassName));
            scheduler.unscheduleJob(TriggerKey.triggerKey(jobClassName));
            scheduler.deleteJob(JobKey.jobKey(jobClassName));
        } catch (java.lang.Exception e) {
            throw new PlatformException("删除定时任务失败");
        }
    }
 
    public static Job getClass(String classname) throws java.lang.Exception {
        Class<?> class1 = Class.forName(classname);
        return (Job)class1.newInstance();
    }
 
}