import java.util.Date; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.apache.log4j.Logger; import org.quartz.JobBuilder; import org.quartz.JobDetail; import org.quartz.JobKey; import org.quartz.Scheduler; import org.quartz.SchedulerException; import org.quartz.SimpleScheduleBuilder; import org.quartz.SimpleTrigger; import org.quartz.Trigger.TriggerState; import org.quartz.TriggerBuilder; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.web.PageableDefault; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; @RestController @RequestMapping("/timer") @Api(tags = "定时任务管理") public class TimerController { public final Logger log = Logger.getLogger(ModuleTimerApplication.class); @Autowired private TimerService timerService; @Autowired private SessionService sessionService; @Autowired private Scheduler scheduler; @GetMapping(value = "/list") @ApiOperation(value = "分页获取列表", produces = MediaType.APPLICATION_JSON_VALUE) public JsonResponse<?> list( @ApiParam(value = StaticFinalStringUtil.AFC_SPECIAL_STRING) @PageableDefault(page = 0, size = 10) Pageable pageable, @ApiParam(value = "任务名", required = false) @RequestParam(name = "timerName", required = false) String timerName, @ApiParam(value = "创建时间", required = false) @RequestParam(name = "createTime", required = false) String createTime, @ApiParam(value = "修改时间", required = false) @RequestParam(name = "lastReviseTime", required = false) String lastReviseTime) { try { Page<Timer> timers = timerService.list(pageable, timerName, createTime, lastReviseTime); List<Timer> list = timers.getContent(); for (Timer timer : list) { timer.setStatus(String.valueOf(getTriggerStatus(timer).ordinal())); } return new JsonResponse<>(timers); } catch (Exception e) { e.printStackTrace(); return new JsonResponse<>(500, e.getMessage()); } } @PostMapping(value = "/add") @ApiOperation(value = "新增", produces = MediaType.APPLICATION_JSON_VALUE) public JsonResponse<?> add(HttpServletRequest request, @ApiParam("") @RequestBody Timer timer) { try { User user = sessionService.getLoginUser(request); timer.setCreateTime(new Date()); timer.setCreator(user.getUserName()); timer.setLastReviser(user.getUserName()); timer.setLastReviseTime(new Date()); // 添加 timer = timerService.save(timer); // 启动 if ("1".equals(timer.getPlanStatus())) { QuartzUtil.startup(timer, scheduler, log); } return new JsonResponse<>(timer); } catch (Exception e) { e.printStackTrace(); return new JsonResponse<>(500, e.getMessage()); } } @PostMapping(value = "/update") @ApiOperation(value = "更新", produces = MediaType.APPLICATION_JSON_VALUE) public JsonResponse<?> update(HttpServletRequest request, @RequestBody Timer t, @RequestParam String id) { try { Timer timer = timerService.findById(id); if (timer == null) { return new JsonResponse<>(400, "找不到该条数据"); } else { Timer oldTimer = new Timer(); BeanUtils.copyProperties(timer, oldTimer); User user = sessionService.getLoginUser(request); timer.setTimerName(t.getTimerName()); timer.setCron(t.getCron()); timer.setDescription(t.getDescription()); timer.setIsConcurrent(t.getIsConcurrent()); timer.setLastReviser(user.getUserName()); timer.setLastReviseTime(new Date()); timer.setPlanStatus(t.getPlanStatus()); timer.setServiceUrl(t.getServiceUrl()); timer.setStatus(t.getStatus()); timer.setTimeDesc(t.getTimeDesc()); timer = timerService.save(timer); deal(oldTimer, timer); return new JsonResponse<>(timer); } } catch (Exception e) { e.printStackTrace(); return new JsonResponse<>(500, e.getMessage()); } } private void deal(Timer oldTimer, Timer newTimer) throws SchedulerException { if (isChanged(oldTimer, newTimer)) { if ("1".equals(oldTimer.getPlanStatus()) && "0".equals(newTimer.getPlanStatus())) { shutdown(oldTimer); } else if ("1".equals(oldTimer.getPlanStatus()) && "1".equals(newTimer.getPlanStatus())) { shutdown(oldTimer); QuartzUtil.startup(newTimer, scheduler, log); } else if ("0".equals(oldTimer.getPlanStatus()) && "1".equals(newTimer.getPlanStatus())) { QuartzUtil.startup(newTimer, scheduler, log); } } } private boolean isChanged(Timer oldTimer, Timer newTimer) { if (oldTimer.getIsConcurrent().equals(newTimer.getIsConcurrent())) { return true; } if (oldTimer.getCron().equals(newTimer.getCron())) { return true; } if (oldTimer.getServiceUrl().equals(newTimer.getServiceUrl())) { return true; } if (oldTimer.getPlanStatus().equals(newTimer.getPlanStatus())) { return true; } return false; } @PostMapping("/delete") @ApiOperation(value = "删除", produces = MediaType.APPLICATION_JSON_VALUE) public JsonResponse<?> delete(@ApiParam(value = "") @RequestParam(required = true) String id) { try { Timer timer = timerService.findById(id); if (null == timer) { return new JsonResponse<>(400, "没有对应记录【id=" + id + "】"); } shutdown(timer);// 删除前先停止运行 timerService.delete(id); return new JsonResponse<>(200, "删除成功"); } catch (Exception e) { e.printStackTrace(); return new JsonResponse<>(500, e.getMessage()); } } @PostMapping(value = "/startup") @ApiOperation(value = "启动", produces = MediaType.APPLICATION_JSON_VALUE) public JsonResponse<?> startup(@ApiParam("定时任务id") @RequestParam String id) { try { Timer timer = timerService.findById(id); if (null == timer) { return new JsonResponse<>(400, "没有对应记录【id=" + id + "】"); } QuartzUtil.startup(timer, scheduler, log); return new JsonResponse<>(timer); } catch (SchedulerException e) { return new JsonResponse<>(400, "操作失败!原因:" + e.getMessage()); } catch (Exception e) { e.printStackTrace(); return new JsonResponse<>(500, e.getMessage()); } } @PostMapping(value = "/shutdown") @ApiOperation(value = "关闭", produces = MediaType.APPLICATION_JSON_VALUE) public JsonResponse<?> shutdown(@ApiParam("定时任务id") @RequestParam String id) { try { Timer timer = timerService.findById(id); if (null == timer) { return new JsonResponse<>(400, "没有对应记录【id=" + id + "】"); } shutdown(timer); return new JsonResponse<>(timer); } catch (SchedulerException e) { return new JsonResponse<>(400, "操作失败!原因:" + e.getMessage()); } catch (Exception e) { e.printStackTrace(); return new JsonResponse<>(500, e.getMessage()); } } private void shutdown(Timer timer) throws SchedulerException { JobKey jobKey = QuartzUtil.getJobKey(timer); scheduler.deleteJob(jobKey); log.info("shutdown:" + timer.getTimerId()); } @PostMapping(value = "/pause") @ApiOperation(value = "暂停", produces = MediaType.APPLICATION_JSON_VALUE) public JsonResponse<?> pause(@ApiParam("定时任务id") @RequestParam String id) { try { Timer timer = timerService.findById(id); if (null == timer) { return new JsonResponse<>(400, "没有对应记录【id=" + id + "】"); } pause(timer); return new JsonResponse<>(timer); } catch (SchedulerException e) { return new JsonResponse<>(400, "操作失败!原因:" + e.getMessage()); } catch (Exception e) { e.printStackTrace(); return new JsonResponse<>(500, e.getMessage()); } } private void pause(Timer timer) throws SchedulerException { JobKey jobKey = QuartzUtil.getJobKey(timer); scheduler.pauseJob(jobKey); log.info("pause:" + timer.getTimerId()); } @PostMapping(value = "/resume") @ApiOperation(value = "恢复", produces = MediaType.APPLICATION_JSON_VALUE) public JsonResponse<?> resume(@ApiParam("定时任务id") @RequestParam String id) { try { Timer timer = timerService.findById(id); if (null == timer) { return new JsonResponse<>(400, "没有对应记录【id=" + id + "】"); } resume(timer); return new JsonResponse<>(timer); } catch (SchedulerException e) { return new JsonResponse<>(400, "操作失败!原因:" + e.getMessage()); } catch (Exception e) { e.printStackTrace(); return new JsonResponse<>(500, e.getMessage()); } } private void resume(Timer timer) throws SchedulerException { JobKey jobKey = QuartzUtil.getJobKey(timer); scheduler.resumeJob(jobKey); log.info("resume:" + timer.getTimerId()); } @PostMapping(value = "/runOnce") @ApiOperation(value = "立即运行一次", produces = MediaType.APPLICATION_JSON_VALUE) public JsonResponse<?> runOnce(@ApiParam("定时任务id") @RequestParam String id) { try { Timer timer = timerService.findById(id); if (null == timer) { return new JsonResponse<>(400, "没有对应记录【id=" + id + "】"); } runOnce(timer); return new JsonResponse<>(timer); } catch (SchedulerException e) { return new JsonResponse<>(400, "操作失败!原因:" + e.getMessage()); } catch (Exception e) { e.printStackTrace(); return new JsonResponse<>(500, e.getMessage()); } } private void runOnce(Timer timer) throws SchedulerException { SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder.simpleSchedule().withRepeatCount(0);// 只执行1次,即重复0次 SimpleTrigger trigger = TriggerBuilder.newTrigger().withSchedule(scheduleBuilder).build(); JobDetail jobDetail = JobBuilder.newJob(timer.getIsConcurrent() ? QuartzConcurrentJob.class : QuartzJob.class) .build(); jobDetail.getJobDataMap().put(QuartzUtil.JOB_DATA_MAP, timer); scheduler.scheduleJob(jobDetail, trigger); log.info("runOnce:" + timer.getTimerId()); } private TriggerState getTriggerStatus(Timer timer) throws SchedulerException { return scheduler.getTriggerState(QuartzUtil.getTriggerKey(timer)); } } |