mirror of
https://github.com/dqjdda/Aurora.git
synced 2018-11-06 05:33:29 +00:00
新增任务调度,调度日志,Aurora v1.1发布
This commit is contained in:
@@ -0,0 +1,141 @@
|
||||
package me.aurora.app.rest.job;
|
||||
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import cn.hutool.http.HttpStatus;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import me.aurora.annotation.Log;
|
||||
import me.aurora.domain.ResponseEntity;
|
||||
import me.aurora.domain.job.Job;
|
||||
import me.aurora.repository.spec.JobSpce;
|
||||
import me.aurora.service.JobService;
|
||||
import me.aurora.util.HttpContextUtils;
|
||||
import org.apache.shiro.authz.annotation.Logical;
|
||||
import org.apache.shiro.authz.annotation.RequiresPermissions;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.servlet.ModelAndView;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* @author 郑杰
|
||||
* @date 2018/10/05 19:12:24
|
||||
*/
|
||||
@Slf4j
|
||||
@RestController
|
||||
@RequestMapping("job")
|
||||
public class JobController {
|
||||
|
||||
@Autowired
|
||||
private JobService jobService;
|
||||
|
||||
/**
|
||||
* 跳转到列表页面
|
||||
* @return
|
||||
*/
|
||||
@GetMapping(value = "/index")
|
||||
public ModelAndView index(){
|
||||
return new ModelAndView("/job/index");
|
||||
}
|
||||
|
||||
@Log("查询所有任务")
|
||||
@RequiresPermissions(value={"admin", "job:all","job:select"}, logical= Logical.OR)
|
||||
@GetMapping(value = "/getJobsInfo")
|
||||
public Map getJobsInfo(@RequestParam(value = "beanName",required = false) String beanName,
|
||||
@RequestParam(value = "methodName",required = false) String methodName,
|
||||
@RequestParam(value = "remark",required = false) String remark,
|
||||
@RequestParam(value = "status",required = false) String status,
|
||||
@RequestParam(value = "page",defaultValue = "1")Integer page,
|
||||
@RequestParam(value = "limit",defaultValue = "10")Integer limit){
|
||||
Sort sort = new Sort(Sort.Direction.ASC,"id");
|
||||
Pageable pageable = PageRequest.of(page-1,limit,sort);
|
||||
return jobService.getJobsInfo(new JobSpce(beanName,methodName,remark,status),pageable);
|
||||
}
|
||||
|
||||
/**
|
||||
* 去新增页面
|
||||
* @return
|
||||
*/
|
||||
@RequiresPermissions (value={"admin", "job:all","job:add"}, logical= Logical.OR)
|
||||
@GetMapping(value = "/toAddPage")
|
||||
public ModelAndView toAddPage(){
|
||||
return new ModelAndView("/job/add");
|
||||
}
|
||||
|
||||
/**
|
||||
* 新增
|
||||
* @param job
|
||||
* @return
|
||||
*/
|
||||
@Log("新增任务")
|
||||
@RequiresPermissions (value={"admin", "job:all","job:add"}, logical= Logical.OR)
|
||||
@PostMapping(value = "/insert")
|
||||
public ResponseEntity insert(@Validated(Job.New.class) @RequestBody Job job){
|
||||
log.warn("REST request to insert Job : {}"+job);
|
||||
jobService.insert(job);
|
||||
return ResponseEntity.ok();
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新状态
|
||||
* @param id
|
||||
* @return
|
||||
*/
|
||||
@Log("更新任务状态")
|
||||
@RequiresPermissions (value={"admin", "job:all","job:status"}, logical= Logical.OR)
|
||||
@PutMapping(value = "/updateStatus")
|
||||
public ResponseEntity updateStatus(@RequestParam Long id){
|
||||
log.warn("REST request to updateStatus Job : {}" +id);
|
||||
jobService.updateStatus(jobService.findById(id));
|
||||
return ResponseEntity.ok();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 去编辑页面
|
||||
* @return
|
||||
*/
|
||||
@RequiresPermissions (value={"admin", "job:all","job:update"}, logical= Logical.OR)
|
||||
@GetMapping(value = "/toUpdatePage")
|
||||
public ModelAndView toUpdatePage(@RequestParam Long id){
|
||||
Job job = jobService.findById(id);
|
||||
// 获取request
|
||||
HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
|
||||
request.setAttribute("job", job);
|
||||
return new ModelAndView("/job/update");
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新任务
|
||||
* @param job
|
||||
* @return
|
||||
*/
|
||||
@Log("更新任务")
|
||||
@RequiresPermissions (value={"admin", "job:all","job:update"}, logical= Logical.OR)
|
||||
@PutMapping(value = "/update")
|
||||
public ResponseEntity update(@Validated(Job.Update.class) @RequestBody Job job) {
|
||||
log.warn("REST request to update Job : {}" +job);
|
||||
jobService.update(jobService.findById(job.getId()),job);
|
||||
return ResponseEntity.ok();
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除任务
|
||||
* @param id
|
||||
* @return
|
||||
*/
|
||||
@Log("删除任务")
|
||||
@RequiresPermissions (value={"admin", "job:all","job:delete"}, logical= Logical.OR)
|
||||
@DeleteMapping(value = "/delete")
|
||||
public ResponseEntity delete(@RequestParam Long id) {
|
||||
log.warn("REST request to delete Job : {}" +id);
|
||||
jobService.delete(jobService.findById(id));
|
||||
return ResponseEntity.ok();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package me.aurora.app.rest.job;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import me.aurora.annotation.Log;
|
||||
import me.aurora.repository.spec.JobLogSpce;
|
||||
import me.aurora.service.JobLogService;
|
||||
import org.apache.shiro.authz.annotation.Logical;
|
||||
import org.apache.shiro.authz.annotation.RequiresPermissions;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.servlet.ModelAndView;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* @author 郑杰
|
||||
* @date 2018/10/06 11:40:21
|
||||
*/
|
||||
@Slf4j
|
||||
@RestController
|
||||
@RequestMapping("jobLog")
|
||||
public class JobLogController {
|
||||
|
||||
@Autowired
|
||||
private JobLogService jobLogService;
|
||||
|
||||
/**
|
||||
* 跳转到列表页面
|
||||
* @return
|
||||
*/
|
||||
@GetMapping(value = "/index")
|
||||
public ModelAndView index(){
|
||||
return new ModelAndView("/job/log");
|
||||
}
|
||||
|
||||
@Log("查询所有任务日志")
|
||||
@RequiresPermissions(value={"admin", "job:all","job:log"}, logical= Logical.OR)
|
||||
@GetMapping(value = "/getJobLogsInfo")
|
||||
public Map getJobLogsInfo(@RequestParam(value = "beanName",required = false) String beanName,
|
||||
@RequestParam(value = "methodName",required = false) String methodName,
|
||||
@RequestParam(value = "remark",required = false) String remark,
|
||||
@RequestParam(value = "status",required = false) String status,
|
||||
@RequestParam(value = "page",defaultValue = "1")Integer page,
|
||||
@RequestParam(value = "limit",defaultValue = "10")Integer limit){
|
||||
Sort sort = new Sort(Sort.Direction.DESC,"id");
|
||||
Pageable pageable = PageRequest.of(page-1,limit,sort);
|
||||
return jobLogService.getJobLogsInfo(new JobLogSpce(beanName,methodName,remark,status),pageable);
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
package me.aurora.config;
|
||||
|
||||
import lombok.Data;
|
||||
import me.aurora.config.scheduled.db.DBProperties;
|
||||
import me.aurora.config.shiro.ShiroProperties;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
@@ -18,8 +17,6 @@ public class AuroraProperties {
|
||||
|
||||
private ShiroProperties shiro = new ShiroProperties();
|
||||
|
||||
private DBProperties db = new DBProperties();
|
||||
|
||||
private Boolean openAopLog;
|
||||
|
||||
private String userAvatar;
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
package me.aurora.config.job;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import me.aurora.domain.job.Job;
|
||||
import me.aurora.repository.JobRepo;
|
||||
import me.aurora.util.job.ScheduleUtils;
|
||||
import org.quartz.Scheduler;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.ApplicationArguments;
|
||||
import org.springframework.boot.ApplicationRunner;
|
||||
import org.springframework.stereotype.Component;
|
||||
import javax.annotation.Resource;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @author 郑杰
|
||||
* @date 2018/10/06 11:09:35
|
||||
*/
|
||||
@Component
|
||||
@Slf4j
|
||||
public class MyJobRunner implements ApplicationRunner {
|
||||
|
||||
@Autowired
|
||||
private JobRepo jobRepo;
|
||||
|
||||
@Resource(name = "scheduler")
|
||||
private Scheduler scheduler;
|
||||
|
||||
/**
|
||||
* 项目启动时重新激活启用的定时任务
|
||||
* @param applicationArguments
|
||||
* @throws Exception
|
||||
*/
|
||||
@Override
|
||||
public void run(ApplicationArguments applicationArguments){
|
||||
List<Job> jobs = jobRepo.findAll();
|
||||
jobs.forEach(scheduleJob -> {
|
||||
ScheduleUtils.createScheduleJob(scheduler, scheduleJob);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package me.aurora.config.job;
|
||||
|
||||
import org.quartz.Scheduler;
|
||||
import org.quartz.spi.TriggerFiredBundle;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.scheduling.quartz.AdaptableJobFactory;
|
||||
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* 定时任务配置
|
||||
* @author 郑杰
|
||||
*/
|
||||
@Configuration
|
||||
public class ScheduleConfig {
|
||||
|
||||
/**
|
||||
* 解决Job中注入Spring Bean为null的问题
|
||||
*/
|
||||
@Component("quartzJobFactory")
|
||||
public class QuartzJobFactory extends AdaptableJobFactory {
|
||||
|
||||
/**
|
||||
* 这个对象Spring会帮我们自动注入进来,也属于Spring技术范畴.
|
||||
*/
|
||||
@Autowired
|
||||
private AutowireCapableBeanFactory capableBeanFactory;
|
||||
|
||||
@Override
|
||||
protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
|
||||
//调用父类的方法
|
||||
Object jobInstance = super.createJobInstance(bundle);
|
||||
//进行注入,这属于Spring的技术,不清楚的可以查看Spring的API.
|
||||
capableBeanFactory.autowireBean(jobInstance);
|
||||
return jobInstance;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 注入scheduler到spring,在下面quartzManege会用到
|
||||
* @param quartzJobFactory
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
@Bean(name = "scheduler")
|
||||
public Scheduler scheduler(QuartzJobFactory quartzJobFactory) throws Exception {
|
||||
|
||||
SchedulerFactoryBean factoryBean=new SchedulerFactoryBean();
|
||||
factoryBean.setJobFactory(quartzJobFactory);
|
||||
factoryBean.afterPropertiesSet();
|
||||
Scheduler scheduler=factoryBean.getScheduler();
|
||||
scheduler.start();
|
||||
return scheduler;
|
||||
}
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
package me.aurora.config.scheduled.db;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* @author 郑杰
|
||||
* @date 2018/09/16 13:59:01
|
||||
*/
|
||||
@Data
|
||||
public class DBProperties {
|
||||
|
||||
private String username;
|
||||
|
||||
private String password;
|
||||
|
||||
private String dbName;
|
||||
|
||||
private String path;
|
||||
|
||||
private String linuxDbPath;
|
||||
|
||||
private String pathName;
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
package me.aurora.config.scheduled.db;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import me.aurora.config.AuroraProperties;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Component;
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
|
||||
/**
|
||||
* @author 郑杰
|
||||
* @date 2018/09/18 11:28:39
|
||||
* 还原数据库
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
public class DBRecover {
|
||||
|
||||
@Autowired
|
||||
private AuroraProperties auroraProperties;
|
||||
|
||||
/**
|
||||
* 还原数据库
|
||||
* @Scheduled(cron = "0 0 1 * * ?")
|
||||
* @Scheduled(cron = "0/5 * * * * ?")
|
||||
*/
|
||||
public void recover(){
|
||||
log.warn("=====>>>>>定时恢复数据库");
|
||||
String path = "";
|
||||
String userName = auroraProperties.getDb().getUsername();
|
||||
String password = auroraProperties.getDb().getPassword();
|
||||
String database = auroraProperties.getDb().getDbName();
|
||||
try {
|
||||
InputStream file = new ClassPathResource(auroraProperties.getDb().getPath()).getInputStream();
|
||||
path = auroraProperties.getDb().getLinuxDbPath()+auroraProperties.getDb().getPathName();
|
||||
Path dBPaht = Paths.get(path);
|
||||
/**
|
||||
* 将本地的sql复制到linux
|
||||
*/
|
||||
Files.copy(file, dBPaht, StandardCopyOption.REPLACE_EXISTING);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
String[] cmd=new String[]{"/bin/sh ","-c ","/usr/bin/mysqldump -u"+userName+" -p"+password+" "+database+ " < " + path};
|
||||
try {
|
||||
Process p = Runtime.getRuntime().exec(cmd);
|
||||
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
|
||||
// 0 表示线程正常终止。
|
||||
if (p.waitFor() == 0) {
|
||||
System.out.println("数据库恢复成功!");
|
||||
} else {
|
||||
System.out.println("数据库恢复失败!");
|
||||
}
|
||||
} catch (Exception e){
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package me.aurora.config.scheduled.task;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* @author 郑杰
|
||||
* @date 2018/10/06 10:03:43
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
public class MyTaskTest {
|
||||
|
||||
public void test(String params) {
|
||||
log.info("我是带参数的test方法,正在被执行,参数为:{}" , params);
|
||||
}
|
||||
|
||||
public void test1() {
|
||||
log.info("我是不带参数的test1方法,正在被执行");
|
||||
}
|
||||
}
|
||||
@@ -22,20 +22,20 @@ public class Dict implements Serializable {
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@NotBlank(groups = {Menu.New.class, Menu.Update.class})
|
||||
@NotBlank(groups = {New.class, Update.class})
|
||||
@Column(name = "table_name",nullable = false)
|
||||
private String tableName;
|
||||
|
||||
@NotBlank(groups = {Menu.New.class, Menu.Update.class})
|
||||
@NotBlank(groups = {New.class, Update.class})
|
||||
@Column(name = "fteld_name",nullable = false)
|
||||
private String fieldName;
|
||||
|
||||
@NotBlank(groups = {Menu.New.class, Menu.Update.class})
|
||||
@NotBlank(groups = {New.class, Update.class})
|
||||
@Column(name = "field_value",nullable = false)
|
||||
private String fieldValue;
|
||||
|
||||
@Column(name = "field_detail",nullable = false)
|
||||
@NotBlank(groups = {Menu.New.class, Menu.Update.class})
|
||||
@NotBlank(groups = {New.class, Update.class})
|
||||
private String fieldDetail;
|
||||
|
||||
@CreationTimestamp
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
package me.aurora.domain.job;
|
||||
|
||||
import com.google.common.base.MoreObjects;
|
||||
import lombok.Data;
|
||||
import org.hibernate.annotations.CreationTimestamp;
|
||||
import org.hibernate.annotations.UpdateTimestamp;
|
||||
|
||||
import javax.persistence.*;
|
||||
import javax.validation.constraints.NotBlank;
|
||||
import java.io.Serializable;
|
||||
import java.sql.Timestamp;
|
||||
|
||||
/**
|
||||
* @author 郑杰
|
||||
* @date 2018/10/05 19:06:42
|
||||
*/
|
||||
@Data
|
||||
@Entity
|
||||
@Table(name = "zj_job")
|
||||
public class Job implements Serializable {
|
||||
|
||||
/**
|
||||
* 任务调度参数key
|
||||
*/
|
||||
public static final String JOB_PARAM_KEY = "JOB_PARAM_KEY";
|
||||
|
||||
public enum ScheduleStatus {
|
||||
/**
|
||||
* 正常
|
||||
*/
|
||||
NORMAL("0"),
|
||||
/**
|
||||
* 暂停
|
||||
*/
|
||||
PAUSE("1");
|
||||
|
||||
private String value;
|
||||
|
||||
private ScheduleStatus(String value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public String getValue() {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
/**
|
||||
* Bean名称
|
||||
*/
|
||||
@Column(name = "baen_name")
|
||||
@NotBlank(groups = {New.class,Update.class})
|
||||
private String beanName;
|
||||
|
||||
/**
|
||||
* 方法名称
|
||||
*/
|
||||
@Column(name = "method_name")
|
||||
@NotBlank(groups = {New.class,Update.class})
|
||||
private String methodName;
|
||||
|
||||
/**
|
||||
* 参数
|
||||
*/
|
||||
@Column(name = "params")
|
||||
private String params;
|
||||
|
||||
/**
|
||||
* cron表达式
|
||||
*/
|
||||
@Column(name = "cron_expression")
|
||||
@NotBlank(groups = {New.class,Update.class})
|
||||
private String cronExpression;
|
||||
|
||||
/**
|
||||
* 状态 0=正常,1=暂停
|
||||
*/
|
||||
@Column(name = "status")
|
||||
@NotBlank(groups = {New.class,Update.class})
|
||||
private String status = "0";
|
||||
|
||||
/**
|
||||
* 备注
|
||||
*/
|
||||
@Column(name = "remark")
|
||||
@NotBlank(groups = {New.class,Update.class})
|
||||
private String remark;
|
||||
|
||||
/**
|
||||
* 创建日期
|
||||
*/
|
||||
@UpdateTimestamp
|
||||
private Timestamp updateTime;
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return MoreObjects.toStringHelper(this)
|
||||
.add("id", id)
|
||||
.add("beanName", beanName)
|
||||
.add("methodName", methodName)
|
||||
.add("params", params)
|
||||
.add("cronExpression", cronExpression)
|
||||
.add("status", status)
|
||||
.add("remark", remark)
|
||||
.add("updateTime", updateTime)
|
||||
.toString();
|
||||
}
|
||||
|
||||
public interface New{};
|
||||
public interface Update{};
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package me.aurora.domain.job;
|
||||
|
||||
import lombok.Data;
|
||||
import org.hibernate.annotations.CreationTimestamp;
|
||||
import javax.persistence.*;
|
||||
import java.io.Serializable;
|
||||
import java.sql.Timestamp;
|
||||
|
||||
/**
|
||||
* @author 郑杰
|
||||
* @date 2018/10/05 19:47:38
|
||||
*/
|
||||
@Entity
|
||||
@Data
|
||||
@Table(name = "zj_job_log")
|
||||
public class JobLog implements Serializable {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
/**
|
||||
* 任务id
|
||||
*/
|
||||
@Column(name = "job_id")
|
||||
private Long jobId;
|
||||
|
||||
/**
|
||||
* Bean名称
|
||||
*/
|
||||
@Column(name = "baen_name")
|
||||
private String beanName;
|
||||
|
||||
/**
|
||||
* 方法名称
|
||||
*/
|
||||
@Column(name = "method_name")
|
||||
private String methodName;
|
||||
|
||||
/**
|
||||
* 参数
|
||||
*/
|
||||
@Column(name = "params")
|
||||
private String params;
|
||||
|
||||
/**
|
||||
* cron表达式
|
||||
*/
|
||||
@Column(name = "cron_expression")
|
||||
private String cronExpression;
|
||||
|
||||
/**
|
||||
* 0=成功,1=失败
|
||||
*/
|
||||
@Column(name = "status")
|
||||
private String status;
|
||||
|
||||
/**
|
||||
* 错误信息
|
||||
*/
|
||||
@Column(name = "error_msg")
|
||||
private String error;
|
||||
|
||||
/**
|
||||
* 耗时(毫秒)
|
||||
*/
|
||||
private Long times;
|
||||
|
||||
/**
|
||||
* 创建日期
|
||||
*/
|
||||
@CreationTimestamp
|
||||
private Timestamp createTime;
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "JobLog{" +
|
||||
"id=" + id +
|
||||
", jobId=" + jobId +
|
||||
", beanName='" + beanName + '\'' +
|
||||
", methodName='" + methodName + '\'' +
|
||||
", params='" + params + '\'' +
|
||||
", cronExpression='" + cronExpression + '\'' +
|
||||
", status='" + status + '\'' +
|
||||
", error='" + error + '\'' +
|
||||
", times=" + times +
|
||||
", createTime=" + createTime +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package me.aurora.repository;
|
||||
|
||||
import me.aurora.domain.job.JobLog;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
|
||||
|
||||
/**
|
||||
* @author 郑杰
|
||||
* @date 2018/10/05 19:52:11
|
||||
*/
|
||||
public interface JobLogRepo extends JpaRepository<JobLog,Long>, JpaSpecificationExecutor {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package me.aurora.repository;
|
||||
|
||||
import me.aurora.domain.job.Job;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @author 郑杰
|
||||
* @date 2018/10/05 19:18:54
|
||||
*/
|
||||
public interface JobRepo extends JpaRepository<Job,Long>, JpaSpecificationExecutor {
|
||||
|
||||
/**
|
||||
* 查找启用的任务
|
||||
* @return
|
||||
*/
|
||||
List<Job> findByStatusIsTrue();
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package me.aurora.repository.spec;
|
||||
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import me.aurora.domain.job.JobLog;
|
||||
import org.springframework.data.jpa.domain.Specification;
|
||||
import javax.persistence.criteria.CriteriaBuilder;
|
||||
import javax.persistence.criteria.CriteriaQuery;
|
||||
import javax.persistence.criteria.Predicate;
|
||||
import javax.persistence.criteria.Root;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
|
||||
/**
|
||||
* @author 郑杰
|
||||
* @date 2018/10/06 11:43:38
|
||||
*/
|
||||
public class JobLogSpce implements Specification<JobLog> {
|
||||
|
||||
private String beanName;
|
||||
private String remark;
|
||||
private String methodName;
|
||||
private String status;
|
||||
|
||||
public JobLogSpce(String beanName, String methodName, String remark, String status) {
|
||||
this.beanName = beanName;
|
||||
this.remark = remark;
|
||||
this.methodName = methodName;
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Predicate toPredicate(Root<JobLog> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder cb) {
|
||||
List<Predicate> list = new ArrayList<Predicate>();
|
||||
|
||||
if (!StrUtil.isEmpty(status)) {
|
||||
list.add(cb.equal(root.get("status").as(String.class), status));
|
||||
}
|
||||
|
||||
if (!StrUtil.isEmpty(beanName)) {
|
||||
list.add(cb.equal(root.get("beanName").as(String.class), "%"+beanName+"%"));
|
||||
}
|
||||
|
||||
if (!StrUtil.isEmpty(remark)) {
|
||||
list.add(cb.like(root.get("remark").as(String.class), "%"+remark+"%"));
|
||||
}
|
||||
|
||||
if (!StrUtil.isEmpty(methodName)) {
|
||||
list.add(cb.equal(root.get("methodName").as(String.class), "%"+methodName+"%"));
|
||||
}
|
||||
|
||||
Predicate[] p = new Predicate[list.size()];
|
||||
return cb.and(list.toArray(p));
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "JobSpce{" +
|
||||
"beanName='" + beanName + '\'' +
|
||||
", remark='" + remark + '\'' +
|
||||
", methodName='" + methodName + '\'' +
|
||||
", status='" + status + '\'' +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package me.aurora.repository.spec;
|
||||
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import me.aurora.domain.Dict;
|
||||
import me.aurora.domain.job.Job;
|
||||
import org.springframework.data.jpa.domain.Specification;
|
||||
|
||||
import javax.persistence.criteria.CriteriaBuilder;
|
||||
import javax.persistence.criteria.CriteriaQuery;
|
||||
import javax.persistence.criteria.Predicate;
|
||||
import javax.persistence.criteria.Root;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
|
||||
/**
|
||||
* @author 郑杰
|
||||
* @date 2018/10/05 19:20:51
|
||||
*/
|
||||
public class JobSpce implements Specification<Job> {
|
||||
|
||||
private String beanName;
|
||||
private String remark;
|
||||
private String methodName;
|
||||
private String status;
|
||||
|
||||
public JobSpce(String beanName, String methodName, String remark, String status) {
|
||||
this.beanName = beanName;
|
||||
this.remark = remark;
|
||||
this.methodName = methodName;
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Predicate toPredicate(Root<Job> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder cb) {
|
||||
List<Predicate> list = new ArrayList<Predicate>();
|
||||
|
||||
|
||||
if (!StrUtil.isEmpty(status)) {
|
||||
list.add(cb.equal(root.get("status").as(String.class), status));
|
||||
}
|
||||
|
||||
if (!StrUtil.isEmpty(beanName)) {
|
||||
list.add(cb.equal(root.get("beanName").as(String.class), "%"+beanName+"%"));
|
||||
}
|
||||
|
||||
if (!StrUtil.isEmpty(methodName)) {
|
||||
list.add(cb.equal(root.get("methodName").as(String.class), "%"+methodName+"%"));
|
||||
}
|
||||
|
||||
if (!StrUtil.isEmpty(remark)) {
|
||||
list.add(cb.like(root.get("remark").as(String.class), "%"+remark+"%"));
|
||||
}
|
||||
|
||||
Predicate[] p = new Predicate[list.size()];
|
||||
return cb.and(list.toArray(p));
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "JobSpce{" +
|
||||
"beanName='" + beanName + '\'' +
|
||||
", remark='" + remark + '\'' +
|
||||
", methodName='" + methodName + '\'' +
|
||||
", status='" + status + '\'' +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package me.aurora.service;
|
||||
|
||||
import me.aurora.domain.job.JobLog;
|
||||
import me.aurora.repository.spec.JobLogSpce;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* @author 郑杰
|
||||
* @date 2018/10/05 19:50:21
|
||||
*/
|
||||
public interface JobLogService {
|
||||
|
||||
/**
|
||||
* 保存日志
|
||||
* @param log
|
||||
*/
|
||||
void insert(JobLog log);
|
||||
|
||||
/**
|
||||
* 查询全部日志
|
||||
* @param jobLogSpce
|
||||
* @param pageable
|
||||
* @return
|
||||
*/
|
||||
Map getJobLogsInfo(JobLogSpce jobLogSpce, Pageable pageable);
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package me.aurora.service;
|
||||
|
||||
import me.aurora.domain.job.Job;
|
||||
import me.aurora.repository.spec.JobSpce;
|
||||
import org.springframework.cache.annotation.CacheConfig;
|
||||
import org.springframework.cache.annotation.CacheEvict;
|
||||
import org.springframework.cache.annotation.Cacheable;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* @author 郑杰
|
||||
* @date 2018/10/05 19:17:38
|
||||
*/
|
||||
@CacheConfig(cacheNames = "job")
|
||||
public interface JobService {
|
||||
|
||||
/**
|
||||
* 查询全部任务
|
||||
* @param jobSpce
|
||||
* @param pageable
|
||||
* @return
|
||||
*/
|
||||
@Cacheable(keyGenerator = "keyGenerator")
|
||||
Map getJobsInfo(JobSpce jobSpce, Pageable pageable);
|
||||
|
||||
/**
|
||||
* 新增任务
|
||||
* @param job
|
||||
*/
|
||||
@CacheEvict(allEntries = true)
|
||||
void insert(Job job);
|
||||
|
||||
/**
|
||||
* 根据ID查询
|
||||
* @param id
|
||||
* @return
|
||||
*/
|
||||
@Cacheable(key = "#p0")
|
||||
Job findById(Long id);
|
||||
|
||||
/**
|
||||
* 更新任务状态
|
||||
* @param byId
|
||||
*/
|
||||
@CacheEvict(allEntries = true)
|
||||
void updateStatus(Job byId);
|
||||
|
||||
/**
|
||||
* 更新任务
|
||||
* @param old
|
||||
* @param job
|
||||
*/
|
||||
@CacheEvict(allEntries = true)
|
||||
void update(Job old, Job job);
|
||||
|
||||
/**
|
||||
* 删除任务
|
||||
* @param byId
|
||||
*/
|
||||
@CacheEvict(allEntries = true)
|
||||
void delete(Job byId);
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package me.aurora.service.impl;
|
||||
|
||||
import me.aurora.domain.job.JobLog;
|
||||
import me.aurora.repository.JobLogRepo;
|
||||
import me.aurora.repository.spec.JobLogSpce;
|
||||
import me.aurora.service.JobLogService;
|
||||
import me.aurora.util.PageUtil;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* @author 郑杰
|
||||
* @date 2018/10/05 19:51:22
|
||||
*/
|
||||
@Service(value = "jobLogService")
|
||||
public class JobLogServiceImpl implements JobLogService {
|
||||
|
||||
@Autowired
|
||||
private JobLogRepo jobLogRepo;
|
||||
|
||||
@Override
|
||||
public void insert(JobLog log) {
|
||||
jobLogRepo.save(log);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map getJobLogsInfo(JobLogSpce jobLogSpce, Pageable pageable) {
|
||||
Page<JobLog> jobLogs = jobLogRepo.findAll(jobLogSpce,pageable);
|
||||
return PageUtil.buildPage(jobLogs.getContent(),jobLogs.getTotalElements());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package me.aurora.service.impl;
|
||||
|
||||
import cn.hutool.http.HttpStatus;
|
||||
import me.aurora.config.exception.AuroraException;
|
||||
import me.aurora.domain.job.Job;
|
||||
import me.aurora.repository.JobRepo;
|
||||
import me.aurora.repository.spec.JobSpce;
|
||||
import me.aurora.service.JobService;
|
||||
import me.aurora.util.PageUtil;
|
||||
import me.aurora.util.ValidationUtil;
|
||||
import me.aurora.util.job.ScheduleUtils;
|
||||
import org.quartz.CronExpression;
|
||||
import org.quartz.Scheduler;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.stereotype.Service;
|
||||
import javax.annotation.Resource;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* @author 郑杰
|
||||
* @date 2018/10/05 19:18:05
|
||||
*/
|
||||
@Service(value = "jobService")
|
||||
public class JobServiceImpl implements JobService {
|
||||
|
||||
@Autowired
|
||||
private JobRepo jobRepo;
|
||||
|
||||
@Resource(name = "scheduler")
|
||||
private Scheduler scheduler;
|
||||
|
||||
@Override
|
||||
public Map getJobsInfo(JobSpce jobSpce, Pageable pageable) {
|
||||
Page<Job> jobs = jobRepo.findAll(jobSpce,pageable);
|
||||
return PageUtil.buildPage(jobs.getContent(),jobs.getTotalElements());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void insert(Job job) {
|
||||
if (!CronExpression.isValidExpression(job.getCronExpression())){
|
||||
throw new AuroraException(HttpStatus.HTTP_BAD_REQUEST,"cron表达式格式错误");
|
||||
}
|
||||
jobRepo.save(job);
|
||||
ScheduleUtils.createScheduleJob(scheduler, job);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Job findById(Long id) {
|
||||
Optional<Job> job = jobRepo.findById(id);
|
||||
ValidationUtil.isNull(job,"id :" +id +" is not find");
|
||||
return job.get();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void updateStatus(Job job) {
|
||||
if (job.getStatus().equals(Job.ScheduleStatus.PAUSE.getValue())) {
|
||||
ScheduleUtils.resumeJob(scheduler, job.getId());
|
||||
job.setStatus("0");
|
||||
} else {
|
||||
ScheduleUtils.pauseJob(scheduler,job.getId());
|
||||
job.setStatus("1");
|
||||
}
|
||||
jobRepo.save(job);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void update(Job old, Job job) {
|
||||
if (!CronExpression.isValidExpression(job.getCronExpression())){
|
||||
throw new AuroraException(HttpStatus.HTTP_BAD_REQUEST,"cron表达式格式错误");
|
||||
}
|
||||
job.setStatus(old.getStatus());
|
||||
jobRepo.save(job);
|
||||
ScheduleUtils.updateScheduleJob(scheduler,job);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete(Job job) {
|
||||
ScheduleUtils.deleteScheduleJob(scheduler,job.getId());
|
||||
jobRepo.delete(job);
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@ import me.aurora.service.mapper.PerMissionMapper;
|
||||
import me.aurora.util.PageUtil;
|
||||
import me.aurora.config.exception.AuroraException;
|
||||
import me.aurora.util.ValidationUtil;
|
||||
import me.aurora.util.job.ScheduleUtils;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
@@ -88,21 +89,22 @@ public class PermissionServiceImpl implements PermissionService {
|
||||
@Override
|
||||
public List<Map<String, Object>> buildPermissionTree(List<Permission> permissions) {
|
||||
List<Map<String,Object>> maps = new LinkedList<>();
|
||||
for (Permission permission:permissions) {
|
||||
if (permission!=null){
|
||||
List<Permission> permissionList = permissionRepo.findByPid(Integer.parseInt(permission.getId()+""));
|
||||
Map<String,Object> map = new HashMap<>(16);
|
||||
map.put("id",permission.getId());
|
||||
String name = !StrUtil.isEmpty(permission.getRemark())?permission.getRemark():permission.getPerms();
|
||||
map.put("name",name);
|
||||
if(permissionList!=null && permissionList.size()!=0){
|
||||
map.put("open",true);
|
||||
map.put("isParent",true);
|
||||
map.put("children",buildPermissionTree(permissionList));
|
||||
permissions.forEach(permission -> {
|
||||
if (permission!=null){
|
||||
List<Permission> permissionList = permissionRepo.findByPid(Integer.parseInt(permission.getId()+""));
|
||||
Map<String,Object> map = new HashMap<>(16);
|
||||
map.put("id",permission.getId());
|
||||
String name = !StrUtil.isEmpty(permission.getRemark())?permission.getRemark():permission.getPerms();
|
||||
map.put("name",name);
|
||||
if(permissionList!=null && permissionList.size()!=0){
|
||||
map.put("open",true);
|
||||
map.put("isParent",true);
|
||||
map.put("children",buildPermissionTree(permissionList));
|
||||
}
|
||||
maps.add(map);
|
||||
}
|
||||
maps.add(map);
|
||||
}
|
||||
}
|
||||
);
|
||||
return maps;
|
||||
}
|
||||
|
||||
|
||||
@@ -36,14 +36,14 @@ public class RoleServiceImpl implements RoleService {
|
||||
@Override
|
||||
public List<Map<String, Object>> buildRoleTree(List<Role> roles) {
|
||||
List<Map<String,Object>> maps = new LinkedList<>();
|
||||
for (Role role:roles) {
|
||||
roles.forEach(role -> {
|
||||
if (role!=null){
|
||||
Map<String,Object> map = new HashMap<>(16);
|
||||
map.put("id",role.getId());
|
||||
map.put("name",role.getName());
|
||||
maps.add(map);
|
||||
}
|
||||
}
|
||||
});
|
||||
return maps;
|
||||
}
|
||||
|
||||
|
||||
@@ -70,10 +70,10 @@ public class UserServiceImpl implements UserService {
|
||||
public Map getUsersInfo(UserSpec userSpec, Pageable pageable) {
|
||||
Page<User> users = userRepo.findAll(userSpec,pageable);
|
||||
List<UserDTO> userDTOS = new ArrayList<>();
|
||||
for(User user:users.getContent()){
|
||||
users.getContent().forEach(user -> {
|
||||
UserDTO userDTO = userMapper.toDto(user,roleService.getRoles(user.getRoles()));
|
||||
userDTOS.add(userDTO);
|
||||
}
|
||||
});
|
||||
return PageUtil.buildPage(userDTOS,users.getTotalElements());
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
package me.aurora.util.job;
|
||||
|
||||
import me.aurora.domain.job.Job;
|
||||
import me.aurora.domain.job.JobLog;
|
||||
import me.aurora.service.JobLogService;
|
||||
import me.aurora.service.JobService;
|
||||
import me.aurora.util.SpringContextUtils;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.quartz.JobExecutionContext;
|
||||
import org.quartz.Scheduler;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.scheduling.quartz.QuartzJobBean;
|
||||
import javax.annotation.Resource;
|
||||
import java.util.concurrent.*;
|
||||
|
||||
/**
|
||||
* 用于记录日志
|
||||
* 定时任务
|
||||
* @author 郑杰
|
||||
*/
|
||||
public class ScheduleJob extends QuartzJobBean {
|
||||
|
||||
@Resource(name = "scheduler")
|
||||
private Scheduler scheduler;
|
||||
|
||||
private Logger logger = LoggerFactory.getLogger(this.getClass());
|
||||
|
||||
private ExecutorService service = Executors.newSingleThreadExecutor();
|
||||
|
||||
@Override
|
||||
protected void executeInternal(JobExecutionContext context) {
|
||||
Job scheduleJob = (Job) context.getMergedJobDataMap().get(Job.JOB_PARAM_KEY);
|
||||
|
||||
// 获取spring bean
|
||||
JobLogService logService = (JobLogService) SpringContextUtils.getBean("jobLogService");
|
||||
JobService jobService = (JobService) SpringContextUtils.getBean("jobService");
|
||||
|
||||
JobLog log = new JobLog();
|
||||
log.setJobId(scheduleJob.getId());
|
||||
log.setBeanName(scheduleJob.getBeanName());
|
||||
log.setMethodName(scheduleJob.getMethodName());
|
||||
log.setParams(scheduleJob.getParams());
|
||||
long startTime = System.currentTimeMillis();
|
||||
log.setCronExpression(scheduleJob.getCronExpression());
|
||||
try {
|
||||
// 执行任务
|
||||
logger.info("任务准备执行,任务ID:{}", scheduleJob.getId());
|
||||
ScheduleRunnable task = new ScheduleRunnable(scheduleJob.getBeanName(), scheduleJob.getMethodName(),
|
||||
scheduleJob.getParams());
|
||||
Future<?> future = service.submit(task);
|
||||
future.get();
|
||||
long times = System.currentTimeMillis() - startTime;
|
||||
log.setTimes(times);
|
||||
// 任务状态 0:成功 1:失败
|
||||
log.setStatus("0");
|
||||
logger.info("任务执行完毕,任务ID:{} 总共耗时:{} 毫秒", scheduleJob.getId(), times);
|
||||
} catch (Exception e) {
|
||||
logger.error("任务执行失败,任务ID:" + scheduleJob.getId(), e);
|
||||
long times = System.currentTimeMillis() - startTime;
|
||||
log.setTimes(times);
|
||||
// 任务状态 0:成功 1:失败
|
||||
log.setStatus("1");
|
||||
log.setError(StringUtils.substring(e.toString(), 0, 2000));
|
||||
//出错就暂停任务
|
||||
ScheduleUtils.pauseJob(scheduler,scheduleJob.getId());
|
||||
//更新状态
|
||||
jobService.updateStatus(scheduleJob);
|
||||
} finally {
|
||||
logService.insert(log);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package me.aurora.util.job;
|
||||
|
||||
import me.aurora.util.SpringContextUtils;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.util.ReflectionUtils;
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
/**
|
||||
* 执行定时任务
|
||||
* @author 郑杰
|
||||
*
|
||||
*/
|
||||
public class ScheduleRunnable implements Runnable {
|
||||
|
||||
private Logger log = LoggerFactory.getLogger(this.getClass());
|
||||
|
||||
private Object target;
|
||||
private Method method;
|
||||
private String params;
|
||||
|
||||
ScheduleRunnable(String beanName, String methodName, String params)
|
||||
throws NoSuchMethodException, SecurityException {
|
||||
this.target = SpringContextUtils.getBean(beanName);
|
||||
this.params = params;
|
||||
|
||||
if (StringUtils.isNotBlank(params)) {
|
||||
this.method = target.getClass().getDeclaredMethod(methodName, String.class);
|
||||
} else {
|
||||
this.method = target.getClass().getDeclaredMethod(methodName);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
ReflectionUtils.makeAccessible(method);
|
||||
if (StringUtils.isNotBlank(params)) {
|
||||
method.invoke(target, params);
|
||||
} else {
|
||||
method.invoke(target);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("执行定时任务失败",e);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
package me.aurora.util.job;
|
||||
|
||||
import cn.hutool.http.HttpStatus;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import me.aurora.config.exception.AuroraException;
|
||||
import me.aurora.domain.job.Job;
|
||||
import org.quartz.*;
|
||||
import org.quartz.impl.triggers.CronTriggerImpl;
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* 定时任务工具类
|
||||
* @author 郑杰
|
||||
*/
|
||||
@Slf4j
|
||||
public class ScheduleUtils {
|
||||
|
||||
protected ScheduleUtils() {
|
||||
}
|
||||
|
||||
private static final String JOB_NAME = "TASK_";
|
||||
|
||||
/**
|
||||
* 获取触发器key
|
||||
*/
|
||||
private static TriggerKey getTriggerKey(Long id) {
|
||||
return TriggerKey.triggerKey(JOB_NAME + id);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取jobKey
|
||||
*/
|
||||
private static JobKey getJobKey(Long id) {
|
||||
return JobKey.jobKey(JOB_NAME + id);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取表达式触发器
|
||||
*/
|
||||
public static CronTrigger getCronTrigger(Scheduler scheduler, Long jobId) {
|
||||
try {
|
||||
return (CronTrigger) scheduler.getTrigger(getTriggerKey(jobId));
|
||||
} catch (SchedulerException e) {
|
||||
log.error("获取Cron表达式失败", e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建定时任务
|
||||
*/
|
||||
public static void createScheduleJob(Scheduler scheduler, Job scheduleJob) {
|
||||
try {
|
||||
// 构建job信息
|
||||
JobDetail jobDetail = JobBuilder.newJob(ScheduleJob.class).withIdentity(getJobKey(scheduleJob.getId()))
|
||||
.build();
|
||||
|
||||
// 表达式调度构建器
|
||||
CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(scheduleJob.getCronExpression())
|
||||
.withMisfireHandlingInstructionDoNothing();
|
||||
|
||||
// 按新的cronExpression表达式构建一个新的trigger
|
||||
CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(getTriggerKey(scheduleJob.getId()))
|
||||
.withSchedule(scheduleBuilder).build();
|
||||
|
||||
// 放入参数,运行时的方法可以获取
|
||||
jobDetail.getJobDataMap().put(Job.JOB_PARAM_KEY, scheduleJob);
|
||||
|
||||
//重置启动时间
|
||||
((CronTriggerImpl)trigger).setStartTime(new Date());
|
||||
|
||||
//执行定时任务
|
||||
scheduler.scheduleJob(jobDetail, trigger);
|
||||
|
||||
// 暂停任务
|
||||
if (scheduleJob.getStatus().equals(Job.ScheduleStatus.PAUSE.getValue())) {
|
||||
pauseJob(scheduler, scheduleJob.getId());
|
||||
}
|
||||
} catch (SchedulerException e) {
|
||||
log.error("创建定时任务失败", e);
|
||||
throw new AuroraException(HttpStatus.HTTP_INTERNAL_ERROR,"创建定时任务失败");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新定时任务
|
||||
*/
|
||||
public static void updateScheduleJob(Scheduler scheduler, Job scheduleJob) {
|
||||
try {
|
||||
TriggerKey triggerKey = getTriggerKey(scheduleJob.getId());
|
||||
|
||||
// 表达式调度构建器
|
||||
CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(scheduleJob.getCronExpression())
|
||||
.withMisfireHandlingInstructionDoNothing();
|
||||
|
||||
CronTrigger trigger = getCronTrigger(scheduler, scheduleJob.getId());
|
||||
|
||||
if (trigger == null) {
|
||||
throw new SchedulerException("获取Cron表达式失败");
|
||||
} else {
|
||||
// 按新的cronExpression表达式重新构建trigger
|
||||
trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();
|
||||
// 参数
|
||||
trigger.getJobDataMap().put(Job.JOB_PARAM_KEY, scheduleJob);
|
||||
}
|
||||
|
||||
//重置启动时间
|
||||
((CronTriggerImpl)trigger).setStartTime(new Date());
|
||||
|
||||
//重置表达式
|
||||
scheduler.rescheduleJob(triggerKey, trigger);
|
||||
|
||||
// 暂停任务
|
||||
if (scheduleJob.getStatus().equals(Job.ScheduleStatus.PAUSE.getValue())) {
|
||||
pauseJob(scheduler, scheduleJob.getId());
|
||||
}
|
||||
|
||||
} catch (SchedulerException e) {
|
||||
log.error("更新定时任务失败", e);
|
||||
throw new AuroraException(HttpStatus.HTTP_INTERNAL_ERROR,"更新定时任务失败");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 立即执行任务
|
||||
*/
|
||||
public static void run(Scheduler scheduler, Job scheduleJob) {
|
||||
try {
|
||||
// 参数
|
||||
JobDataMap dataMap = new JobDataMap();
|
||||
dataMap.put(Job.JOB_PARAM_KEY, scheduleJob);
|
||||
|
||||
scheduler.triggerJob(getJobKey(scheduleJob.getId()), dataMap);
|
||||
} catch (SchedulerException e) {
|
||||
log.error("执行定时任务失败", e);
|
||||
throw new AuroraException(HttpStatus.HTTP_INTERNAL_ERROR,"执行定时任务失败");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 暂停任务
|
||||
*/
|
||||
public static void pauseJob(Scheduler scheduler, Long jobId) {
|
||||
try {
|
||||
scheduler.pauseJob(getJobKey(jobId));
|
||||
} catch (SchedulerException e) {
|
||||
log.error("暂停定时任务失败", e);
|
||||
throw new AuroraException(HttpStatus.HTTP_INTERNAL_ERROR,"暂停定时任务失败");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 恢复任务
|
||||
*/
|
||||
public static void resumeJob(Scheduler scheduler, Long jobId) {
|
||||
try {
|
||||
scheduler.resumeJob(getJobKey(jobId));
|
||||
} catch (SchedulerException e) {
|
||||
log.error("恢复定时任务失败", e);
|
||||
throw new AuroraException(HttpStatus.HTTP_INTERNAL_ERROR,"恢复定时任务失败");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除定时任务
|
||||
*/
|
||||
public static void deleteScheduleJob(Scheduler scheduler, Long jobId) {
|
||||
try {
|
||||
scheduler.deleteJob(getJobKey(jobId));
|
||||
} catch (SchedulerException e) {
|
||||
log.error("删除定时任务失败", e);
|
||||
throw new AuroraException(HttpStatus.HTTP_INTERNAL_ERROR,"删除定时任务失败");
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user