收银后台上传!
This commit is contained in:
@@ -0,0 +1,51 @@
|
||||
/*
|
||||
* Copyright 2019-2020 Zheng Jie
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package me.zhengjie.modules.quartz.config;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import me.zhengjie.modules.quartz.domain.QuartzJob;
|
||||
import me.zhengjie.modules.quartz.repository.QuartzJobRepository;
|
||||
import me.zhengjie.modules.quartz.utils.QuartzManage;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.boot.ApplicationArguments;
|
||||
import org.springframework.boot.ApplicationRunner;
|
||||
import org.springframework.stereotype.Component;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @author Zheng Jie
|
||||
* @date 2019-01-07
|
||||
*/
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class JobRunner implements ApplicationRunner {
|
||||
private static final Logger log = LoggerFactory.getLogger(JobRunner.class);
|
||||
private final QuartzJobRepository quartzJobRepository;
|
||||
private final QuartzManage quartzManage;
|
||||
|
||||
/**
|
||||
* 项目启动时重新激活启用的定时任务
|
||||
*
|
||||
* @param applicationArguments /
|
||||
*/
|
||||
@Override
|
||||
public void run(ApplicationArguments applicationArguments) {
|
||||
List<QuartzJob> quartzJobs = quartzJobRepository.findByIsPauseIsFalse();
|
||||
quartzJobs.forEach(quartzManage::addJob);
|
||||
log.info("Timing task injection complete");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
/*
|
||||
* Copyright 2019-2020 Zheng Jie
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package me.zhengjie.modules.quartz.config;
|
||||
|
||||
import org.quartz.spi.TriggerFiredBundle;
|
||||
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.scheduling.quartz.AdaptableJobFactory;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* 定时任务配置
|
||||
* @author /
|
||||
* @date 2019-01-07
|
||||
*/
|
||||
@Configuration
|
||||
public class QuartzConfig {
|
||||
|
||||
/**
|
||||
* 解决Job中注入Spring Bean为null的问题
|
||||
*/
|
||||
@Component("quartzJobFactory")
|
||||
public static class QuartzJobFactory extends AdaptableJobFactory {
|
||||
|
||||
private final AutowireCapableBeanFactory capableBeanFactory;
|
||||
|
||||
public QuartzJobFactory(AutowireCapableBeanFactory capableBeanFactory) {
|
||||
this.capableBeanFactory = capableBeanFactory;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
|
||||
//调用父类的方法,把Job注入到spring中
|
||||
Object jobInstance = super.createJobInstance(bundle);
|
||||
capableBeanFactory.autowireBean(jobInstance);
|
||||
return jobInstance;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
/*
|
||||
* Copyright 2019-2020 Zheng Jie
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package me.zhengjie.modules.quartz.domain;
|
||||
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import me.zhengjie.base.BaseEntity;
|
||||
import javax.persistence.*;
|
||||
import javax.validation.constraints.NotBlank;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* @author Zheng Jie
|
||||
* @date 2019-01-07
|
||||
*/
|
||||
@Getter
|
||||
@Setter
|
||||
@Entity
|
||||
@Table(name = "sys_quartz_job")
|
||||
public class QuartzJob extends BaseEntity implements Serializable {
|
||||
|
||||
public static final String JOB_KEY = "JOB_KEY";
|
||||
|
||||
@Id
|
||||
@Column(name = "job_id")
|
||||
@NotNull(groups = {Update.class})
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@Transient
|
||||
@ApiModelProperty(value = "用于子任务唯一标识", hidden = true)
|
||||
private String uuid;
|
||||
|
||||
@ApiModelProperty(value = "定时器名称")
|
||||
private String jobName;
|
||||
|
||||
@NotBlank
|
||||
@ApiModelProperty(value = "Bean名称")
|
||||
private String beanName;
|
||||
|
||||
@NotBlank
|
||||
@ApiModelProperty(value = "方法名称")
|
||||
private String methodName;
|
||||
|
||||
@ApiModelProperty(value = "参数")
|
||||
private String params;
|
||||
|
||||
@NotBlank
|
||||
@ApiModelProperty(value = "cron表达式")
|
||||
private String cronExpression;
|
||||
|
||||
@ApiModelProperty(value = "状态,暂时或启动")
|
||||
private Boolean isPause = false;
|
||||
|
||||
@ApiModelProperty(value = "负责人")
|
||||
private String personInCharge;
|
||||
|
||||
@ApiModelProperty(value = "报警邮箱")
|
||||
private String email;
|
||||
|
||||
@ApiModelProperty(value = "子任务")
|
||||
private String subTask;
|
||||
|
||||
@ApiModelProperty(value = "失败后暂停")
|
||||
private Boolean pauseAfterFailure;
|
||||
|
||||
@NotBlank
|
||||
@ApiModelProperty(value = "备注")
|
||||
private String description;
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
/*
|
||||
* Copyright 2019-2020 Zheng Jie
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package me.zhengjie.modules.quartz.domain;
|
||||
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import lombok.Data;
|
||||
import org.hibernate.annotations.CreationTimestamp;
|
||||
import javax.persistence.*;
|
||||
import java.io.Serializable;
|
||||
import java.sql.Timestamp;
|
||||
|
||||
/**
|
||||
* @author Zheng Jie
|
||||
* @date 2019-01-07
|
||||
*/
|
||||
@Entity
|
||||
@Data
|
||||
@Table(name = "sys_quartz_log")
|
||||
public class QuartzLog implements Serializable {
|
||||
|
||||
@Id
|
||||
@Column(name = "log_id")
|
||||
@ApiModelProperty(value = "ID", hidden = true)
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@ApiModelProperty(value = "任务名称", hidden = true)
|
||||
private String jobName;
|
||||
|
||||
@ApiModelProperty(value = "bean名称", hidden = true)
|
||||
private String beanName;
|
||||
|
||||
@ApiModelProperty(value = "方法名称", hidden = true)
|
||||
private String methodName;
|
||||
|
||||
@ApiModelProperty(value = "参数", hidden = true)
|
||||
private String params;
|
||||
|
||||
@ApiModelProperty(value = "cron表达式", hidden = true)
|
||||
private String cronExpression;
|
||||
|
||||
@ApiModelProperty(value = "状态", hidden = true)
|
||||
private Boolean isSuccess;
|
||||
|
||||
@ApiModelProperty(value = "异常详情", hidden = true)
|
||||
private String exceptionDetail;
|
||||
|
||||
@ApiModelProperty(value = "执行耗时", hidden = true)
|
||||
private Long time;
|
||||
|
||||
@CreationTimestamp
|
||||
@ApiModelProperty(value = "创建时间", hidden = true)
|
||||
private Timestamp createTime;
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
/*
|
||||
* Copyright 2019-2020 Zheng Jie
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package me.zhengjie.modules.quartz.repository;
|
||||
|
||||
import me.zhengjie.modules.quartz.domain.QuartzJob;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @author Zheng Jie
|
||||
* @date 2019-01-07
|
||||
*/
|
||||
public interface QuartzJobRepository extends JpaRepository<QuartzJob,Long>, JpaSpecificationExecutor<QuartzJob> {
|
||||
|
||||
/**
|
||||
* 查询启用的任务
|
||||
* @return List
|
||||
*/
|
||||
List<QuartzJob> findByIsPauseIsFalse();
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
/*
|
||||
* Copyright 2019-2020 Zheng Jie
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package me.zhengjie.modules.quartz.repository;
|
||||
|
||||
import me.zhengjie.modules.quartz.domain.QuartzLog;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
|
||||
|
||||
/**
|
||||
* @author Zheng Jie
|
||||
* @date 2019-01-07
|
||||
*/
|
||||
public interface QuartzLogRepository extends JpaRepository<QuartzLog,Long>, JpaSpecificationExecutor<QuartzLog> {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
/*
|
||||
* Copyright 2019-2020 Zheng Jie
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package me.zhengjie.modules.quartz.rest;
|
||||
|
||||
import io.swagger.annotations.Api;
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import me.zhengjie.annotation.Log;
|
||||
import me.zhengjie.exception.BadRequestException;
|
||||
import me.zhengjie.modules.quartz.domain.QuartzJob;
|
||||
import me.zhengjie.modules.quartz.service.QuartzJobService;
|
||||
import me.zhengjie.modules.quartz.service.dto.JobQueryCriteria;
|
||||
import me.zhengjie.utils.SpringContextHolder;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* @author Zheng Jie
|
||||
* @date 2019-01-07
|
||||
*/
|
||||
@Slf4j
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@RequestMapping("/api/jobs")
|
||||
@Api(tags = "系统:定时任务管理")
|
||||
public class QuartzJobController {
|
||||
|
||||
private static final String ENTITY_NAME = "quartzJob";
|
||||
private final QuartzJobService quartzJobService;
|
||||
|
||||
@ApiOperation("查询定时任务")
|
||||
@GetMapping
|
||||
@PreAuthorize("@el.check('timing:list')")
|
||||
public ResponseEntity<Object> queryQuartzJob(JobQueryCriteria criteria, Pageable pageable){
|
||||
return new ResponseEntity<>(quartzJobService.queryAll(criteria,pageable), HttpStatus.OK);
|
||||
}
|
||||
|
||||
@ApiOperation("导出任务数据")
|
||||
@GetMapping(value = "/download")
|
||||
@PreAuthorize("@el.check('timing:list')")
|
||||
public void exportQuartzJob(HttpServletResponse response, JobQueryCriteria criteria) throws IOException {
|
||||
quartzJobService.download(quartzJobService.queryAll(criteria), response);
|
||||
}
|
||||
|
||||
@ApiOperation("导出日志数据")
|
||||
@GetMapping(value = "/logs/download")
|
||||
@PreAuthorize("@el.check('timing:list')")
|
||||
public void exportQuartzJobLog(HttpServletResponse response, JobQueryCriteria criteria) throws IOException {
|
||||
quartzJobService.downloadLog(quartzJobService.queryAllLog(criteria), response);
|
||||
}
|
||||
|
||||
@ApiOperation("查询任务执行日志")
|
||||
@GetMapping(value = "/logs")
|
||||
@PreAuthorize("@el.check('timing:list')")
|
||||
public ResponseEntity<Object> queryQuartzJobLog(JobQueryCriteria criteria, Pageable pageable){
|
||||
return new ResponseEntity<>(quartzJobService.queryAllLog(criteria,pageable), HttpStatus.OK);
|
||||
}
|
||||
|
||||
@Log("新增定时任务")
|
||||
@ApiOperation("新增定时任务")
|
||||
@PostMapping
|
||||
@PreAuthorize("@el.check('timing:add')")
|
||||
public ResponseEntity<Object> createQuartzJob(@Validated @RequestBody QuartzJob resources){
|
||||
if (resources.getId() != null) {
|
||||
throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID");
|
||||
}
|
||||
// 验证Bean是不是合法的,合法的定时任务 Bean 需要用 @Service 定义
|
||||
checkBean(resources.getBeanName());
|
||||
quartzJobService.create(resources);
|
||||
return new ResponseEntity<>(HttpStatus.CREATED);
|
||||
}
|
||||
|
||||
@Log("修改定时任务")
|
||||
@ApiOperation("修改定时任务")
|
||||
@PutMapping
|
||||
@PreAuthorize("@el.check('timing:edit')")
|
||||
public ResponseEntity<Object> updateQuartzJob(@Validated(QuartzJob.Update.class) @RequestBody QuartzJob resources){
|
||||
// 验证Bean是不是合法的,合法的定时任务 Bean 需要用 @Service 定义
|
||||
checkBean(resources.getBeanName());
|
||||
quartzJobService.update(resources);
|
||||
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
|
||||
}
|
||||
|
||||
@Log("更改定时任务状态")
|
||||
@ApiOperation("更改定时任务状态")
|
||||
@PutMapping(value = "/{id}")
|
||||
@PreAuthorize("@el.check('timing:edit')")
|
||||
public ResponseEntity<Object> updateQuartzJobStatus(@PathVariable Long id){
|
||||
quartzJobService.updateIsPause(quartzJobService.findById(id));
|
||||
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
|
||||
}
|
||||
|
||||
@Log("执行定时任务")
|
||||
@ApiOperation("执行定时任务")
|
||||
@PutMapping(value = "/exec/{id}")
|
||||
@PreAuthorize("@el.check('timing:edit')")
|
||||
public ResponseEntity<Object> executionQuartzJob(@PathVariable Long id){
|
||||
quartzJobService.execution(quartzJobService.findById(id));
|
||||
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
|
||||
}
|
||||
|
||||
@Log("删除定时任务")
|
||||
@ApiOperation("删除定时任务")
|
||||
@DeleteMapping
|
||||
@PreAuthorize("@el.check('timing:del')")
|
||||
public ResponseEntity<Object> deleteQuartzJob(@RequestBody Set<Long> ids){
|
||||
quartzJobService.delete(ids);
|
||||
return new ResponseEntity<>(HttpStatus.OK);
|
||||
}
|
||||
|
||||
private void checkBean(String beanName){
|
||||
// 避免调用攻击者可以从SpringContextHolder获得控制jdbcTemplate类
|
||||
// 并使用getDeclaredMethod调用jdbcTemplate的queryForMap函数,执行任意sql命令。
|
||||
if(!SpringContextHolder.getAllServiceBeanName().contains(beanName)){
|
||||
throw new BadRequestException("非法的 Bean,请重新输入!");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
/*
|
||||
* Copyright 2019-2020 Zheng Jie
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package me.zhengjie.modules.quartz.service;
|
||||
|
||||
import me.zhengjie.modules.quartz.domain.QuartzJob;
|
||||
import me.zhengjie.modules.quartz.domain.QuartzLog;
|
||||
import me.zhengjie.modules.quartz.service.dto.JobQueryCriteria;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* @author Zheng Jie
|
||||
* @date 2019-01-07
|
||||
*/
|
||||
public interface QuartzJobService {
|
||||
|
||||
/**
|
||||
* 分页查询
|
||||
* @param criteria 条件
|
||||
* @param pageable 分页参数
|
||||
* @return /
|
||||
*/
|
||||
Object queryAll(JobQueryCriteria criteria, Pageable pageable);
|
||||
|
||||
/**
|
||||
* 查询全部
|
||||
* @param criteria 条件
|
||||
* @return /
|
||||
*/
|
||||
List<QuartzJob> queryAll(JobQueryCriteria criteria);
|
||||
|
||||
/**
|
||||
* 分页查询日志
|
||||
* @param criteria 条件
|
||||
* @param pageable 分页参数
|
||||
* @return /
|
||||
*/
|
||||
Object queryAllLog(JobQueryCriteria criteria, Pageable pageable);
|
||||
|
||||
/**
|
||||
* 查询全部
|
||||
* @param criteria 条件
|
||||
* @return /
|
||||
*/
|
||||
List<QuartzLog> queryAllLog(JobQueryCriteria criteria);
|
||||
|
||||
/**
|
||||
* 创建
|
||||
* @param resources /
|
||||
*/
|
||||
void create(QuartzJob resources);
|
||||
|
||||
/**
|
||||
* 编辑
|
||||
* @param resources /
|
||||
*/
|
||||
void update(QuartzJob resources);
|
||||
|
||||
/**
|
||||
* 删除任务
|
||||
* @param ids /
|
||||
*/
|
||||
void delete(Set<Long> ids);
|
||||
|
||||
/**
|
||||
* 根据ID查询
|
||||
* @param id ID
|
||||
* @return /
|
||||
*/
|
||||
QuartzJob findById(Long id);
|
||||
|
||||
/**
|
||||
* 更改定时任务状态
|
||||
* @param quartzJob /
|
||||
*/
|
||||
void updateIsPause(QuartzJob quartzJob);
|
||||
|
||||
/**
|
||||
* 立即执行定时任务
|
||||
* @param quartzJob /
|
||||
*/
|
||||
void execution(QuartzJob quartzJob);
|
||||
|
||||
/**
|
||||
* 导出定时任务
|
||||
* @param queryAll 待导出的数据
|
||||
* @param response /
|
||||
* @throws IOException /
|
||||
*/
|
||||
void download(List<QuartzJob> queryAll, HttpServletResponse response) throws IOException;
|
||||
|
||||
/**
|
||||
* 导出定时任务日志
|
||||
* @param queryAllLog 待导出的数据
|
||||
* @param response /
|
||||
* @throws IOException /
|
||||
*/
|
||||
void downloadLog(List<QuartzLog> queryAllLog, HttpServletResponse response) throws IOException;
|
||||
|
||||
/**
|
||||
* 执行子任务
|
||||
* @param tasks /
|
||||
* @throws InterruptedException /
|
||||
*/
|
||||
void executionSubJob(String[] tasks) throws InterruptedException;
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
/*
|
||||
* Copyright 2019-2020 Zheng Jie
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package me.zhengjie.modules.quartz.service.dto;
|
||||
|
||||
import lombok.Data;
|
||||
import me.zhengjie.annotation.Query;
|
||||
import java.sql.Timestamp;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @author Zheng Jie
|
||||
* @date 2019-6-4 10:33:02
|
||||
*/
|
||||
@Data
|
||||
public class JobQueryCriteria {
|
||||
|
||||
@Query(type = Query.Type.INNER_LIKE)
|
||||
private String jobName;
|
||||
|
||||
@Query
|
||||
private Boolean isSuccess;
|
||||
|
||||
@Query(type = Query.Type.BETWEEN)
|
||||
private List<Timestamp> createTime;
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
/*
|
||||
* Copyright 2019-2020 Zheng Jie
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package me.zhengjie.modules.quartz.service.impl;
|
||||
|
||||
import cn.hutool.core.util.IdUtil;
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import me.zhengjie.exception.BadRequestException;
|
||||
import me.zhengjie.modules.quartz.domain.QuartzJob;
|
||||
import me.zhengjie.modules.quartz.domain.QuartzLog;
|
||||
import me.zhengjie.modules.quartz.repository.QuartzJobRepository;
|
||||
import me.zhengjie.modules.quartz.repository.QuartzLogRepository;
|
||||
import me.zhengjie.modules.quartz.service.QuartzJobService;
|
||||
import me.zhengjie.modules.quartz.service.dto.JobQueryCriteria;
|
||||
import me.zhengjie.modules.quartz.utils.QuartzManage;
|
||||
import me.zhengjie.utils.*;
|
||||
import org.quartz.CronExpression;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.scheduling.annotation.Async;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* @author Zheng Jie
|
||||
* @date 2019-01-07
|
||||
*/
|
||||
@RequiredArgsConstructor
|
||||
@Service(value = "quartzJobService")
|
||||
public class QuartzJobServiceImpl implements QuartzJobService {
|
||||
|
||||
private final QuartzJobRepository quartzJobRepository;
|
||||
private final QuartzLogRepository quartzLogRepository;
|
||||
private final QuartzManage quartzManage;
|
||||
private final RedisUtils redisUtils;
|
||||
|
||||
@Override
|
||||
public Object queryAll(JobQueryCriteria criteria, Pageable pageable){
|
||||
return PageUtil.toPage(quartzJobRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object queryAllLog(JobQueryCriteria criteria, Pageable pageable){
|
||||
return PageUtil.toPage(quartzLogRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable));
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<QuartzJob> queryAll(JobQueryCriteria criteria) {
|
||||
return quartzJobRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder));
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<QuartzLog> queryAllLog(JobQueryCriteria criteria) {
|
||||
return quartzLogRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder));
|
||||
}
|
||||
|
||||
@Override
|
||||
public QuartzJob findById(Long id) {
|
||||
QuartzJob quartzJob = quartzJobRepository.findById(id).orElseGet(QuartzJob::new);
|
||||
ValidationUtil.isNull(quartzJob.getId(),"QuartzJob","id",id);
|
||||
return quartzJob;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void create(QuartzJob resources) {
|
||||
if (!CronExpression.isValidExpression(resources.getCronExpression())){
|
||||
throw new BadRequestException("cron表达式格式错误");
|
||||
}
|
||||
resources = quartzJobRepository.save(resources);
|
||||
quartzManage.addJob(resources);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void update(QuartzJob resources) {
|
||||
if (!CronExpression.isValidExpression(resources.getCronExpression())){
|
||||
throw new BadRequestException("cron表达式格式错误");
|
||||
}
|
||||
if(StringUtils.isNotBlank(resources.getSubTask())){
|
||||
List<String> tasks = Arrays.asList(resources.getSubTask().split("[,,]"));
|
||||
if (tasks.contains(resources.getId().toString())) {
|
||||
throw new BadRequestException("子任务中不能添加当前任务ID");
|
||||
}
|
||||
}
|
||||
resources = quartzJobRepository.save(resources);
|
||||
quartzManage.updateJobCron(resources);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void updateIsPause(QuartzJob quartzJob) {
|
||||
if (quartzJob.getIsPause()) {
|
||||
quartzManage.resumeJob(quartzJob);
|
||||
quartzJob.setIsPause(false);
|
||||
} else {
|
||||
quartzManage.pauseJob(quartzJob);
|
||||
quartzJob.setIsPause(true);
|
||||
}
|
||||
quartzJobRepository.save(quartzJob);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execution(QuartzJob quartzJob) {
|
||||
quartzManage.runJobNow(quartzJob);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void delete(Set<Long> ids) {
|
||||
for (Long id : ids) {
|
||||
QuartzJob quartzJob = findById(id);
|
||||
quartzManage.deleteJob(quartzJob);
|
||||
quartzJobRepository.delete(quartzJob);
|
||||
}
|
||||
}
|
||||
|
||||
@Async
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void executionSubJob(String[] tasks) throws InterruptedException {
|
||||
for (String id : tasks) {
|
||||
if (StrUtil.isBlank(id)) {
|
||||
// 如果是手动清除子任务id,会出现id为空字符串的问题
|
||||
continue;
|
||||
}
|
||||
QuartzJob quartzJob = findById(Long.parseLong(id));
|
||||
// 执行任务
|
||||
String uuid = IdUtil.simpleUUID();
|
||||
quartzJob.setUuid(uuid);
|
||||
// 执行任务
|
||||
execution(quartzJob);
|
||||
// 获取执行状态,如果执行失败则停止后面的子任务执行
|
||||
Boolean result = (Boolean) redisUtils.get(uuid);
|
||||
while (result == null) {
|
||||
// 休眠5秒,再次获取子任务执行情况
|
||||
Thread.sleep(5000);
|
||||
result = (Boolean) redisUtils.get(uuid);
|
||||
}
|
||||
if(!result){
|
||||
redisUtils.del(uuid);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void download(List<QuartzJob> quartzJobs, HttpServletResponse response) throws IOException {
|
||||
List<Map<String, Object>> list = new ArrayList<>();
|
||||
for (QuartzJob quartzJob : quartzJobs) {
|
||||
Map<String,Object> map = new LinkedHashMap<>();
|
||||
map.put("任务名称", quartzJob.getJobName());
|
||||
map.put("Bean名称", quartzJob.getBeanName());
|
||||
map.put("执行方法", quartzJob.getMethodName());
|
||||
map.put("参数", quartzJob.getParams());
|
||||
map.put("表达式", quartzJob.getCronExpression());
|
||||
map.put("状态", quartzJob.getIsPause() ? "暂停中" : "运行中");
|
||||
map.put("描述", quartzJob.getDescription());
|
||||
map.put("创建日期", quartzJob.getCreateTime());
|
||||
list.add(map);
|
||||
}
|
||||
FileUtil.downloadExcel(list, response);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void downloadLog(List<QuartzLog> queryAllLog, HttpServletResponse response) throws IOException {
|
||||
List<Map<String, Object>> list = new ArrayList<>();
|
||||
for (QuartzLog quartzLog : queryAllLog) {
|
||||
Map<String,Object> map = new LinkedHashMap<>();
|
||||
map.put("任务名称", quartzLog.getJobName());
|
||||
map.put("Bean名称", quartzLog.getBeanName());
|
||||
map.put("执行方法", quartzLog.getMethodName());
|
||||
map.put("参数", quartzLog.getParams());
|
||||
map.put("表达式", quartzLog.getCronExpression());
|
||||
map.put("异常详情", quartzLog.getExceptionDetail());
|
||||
map.put("耗时/毫秒", quartzLog.getTime());
|
||||
map.put("状态", quartzLog.getIsSuccess() ? "成功" : "失败");
|
||||
map.put("创建日期", quartzLog.getCreateTime());
|
||||
list.add(map);
|
||||
}
|
||||
FileUtil.downloadExcel(list, response);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
/*
|
||||
* Copyright 2019-2020 Zheng Jie
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package me.zhengjie.modules.quartz.task;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
/**
|
||||
* 测试用
|
||||
* @author Zheng Jie
|
||||
* @date 2019-01-08
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
public class TestTask {
|
||||
|
||||
public void run(){
|
||||
log.info("run 执行成功");
|
||||
}
|
||||
|
||||
public void run1(String str){
|
||||
log.info("run1 执行成功,参数为: {}" + str);
|
||||
}
|
||||
|
||||
public void run2(){
|
||||
log.info("run2 执行成功");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
/*
|
||||
* Copyright 2019-2020 Zheng Jie
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package me.zhengjie.modules.quartz.utils;
|
||||
|
||||
import cn.hutool.extra.template.Template;
|
||||
import cn.hutool.extra.template.TemplateConfig;
|
||||
import cn.hutool.extra.template.TemplateEngine;
|
||||
import cn.hutool.extra.template.TemplateUtil;
|
||||
import me.zhengjie.config.thread.ThreadPoolExecutorUtil;
|
||||
import me.zhengjie.domain.vo.EmailVo;
|
||||
import me.zhengjie.modules.quartz.domain.QuartzJob;
|
||||
import me.zhengjie.modules.quartz.domain.QuartzLog;
|
||||
import me.zhengjie.modules.quartz.repository.QuartzLogRepository;
|
||||
import me.zhengjie.modules.quartz.service.QuartzJobService;
|
||||
import me.zhengjie.service.EmailService;
|
||||
import me.zhengjie.utils.RedisUtils;
|
||||
import me.zhengjie.utils.SpringContextHolder;
|
||||
import me.zhengjie.utils.StringUtils;
|
||||
import me.zhengjie.utils.ThrowableUtil;
|
||||
import org.quartz.JobExecutionContext;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.scheduling.quartz.QuartzJobBean;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
|
||||
/**
|
||||
* 参考人人开源,https://gitee.com/renrenio/renren-security
|
||||
* @author /
|
||||
* @date 2019-01-07
|
||||
*/
|
||||
public class ExecutionJob extends QuartzJobBean {
|
||||
|
||||
private final Logger logger = LoggerFactory.getLogger(this.getClass());
|
||||
|
||||
// 此处仅供参考,可根据任务执行情况自定义线程池参数
|
||||
private final static ExecutorService executor = ThreadPoolExecutorUtil.getPoll("el-quartz-job");
|
||||
|
||||
@Override
|
||||
public void executeInternal(JobExecutionContext context) {
|
||||
// 获取任务
|
||||
QuartzJob quartzJob = (QuartzJob) context.getMergedJobDataMap().get(QuartzJob.JOB_KEY);
|
||||
// 获取spring bean
|
||||
QuartzLogRepository quartzLogRepository = SpringContextHolder.getBean(QuartzLogRepository.class);
|
||||
QuartzJobService quartzJobService = SpringContextHolder.getBean(QuartzJobService.class);
|
||||
RedisUtils redisUtils = SpringContextHolder.getBean(RedisUtils.class);
|
||||
|
||||
String uuid = quartzJob.getUuid();
|
||||
|
||||
QuartzLog log = new QuartzLog();
|
||||
log.setJobName(quartzJob.getJobName());
|
||||
log.setBeanName(quartzJob.getBeanName());
|
||||
log.setMethodName(quartzJob.getMethodName());
|
||||
log.setParams(quartzJob.getParams());
|
||||
long startTime = System.currentTimeMillis();
|
||||
log.setCronExpression(quartzJob.getCronExpression());
|
||||
try {
|
||||
// 执行任务
|
||||
QuartzRunnable task = new QuartzRunnable(quartzJob.getBeanName(), quartzJob.getMethodName(), quartzJob.getParams());
|
||||
Future<?> future = executor.submit(task);
|
||||
future.get();
|
||||
long times = System.currentTimeMillis() - startTime;
|
||||
log.setTime(times);
|
||||
if(StringUtils.isNotBlank(uuid)) {
|
||||
redisUtils.set(uuid, true);
|
||||
}
|
||||
// 任务状态
|
||||
log.setIsSuccess(true);
|
||||
logger.info("任务执行成功,任务名称:" + quartzJob.getJobName() + ", 执行时间:" + times + "毫秒");
|
||||
// 判断是否存在子任务
|
||||
if(StringUtils.isNotBlank(quartzJob.getSubTask())){
|
||||
String[] tasks = quartzJob.getSubTask().split("[,,]");
|
||||
// 执行子任务
|
||||
quartzJobService.executionSubJob(tasks);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
if(StringUtils.isNotBlank(uuid)) {
|
||||
redisUtils.set(uuid, false);
|
||||
}
|
||||
logger.error("任务执行失败,任务名称:" + quartzJob.getJobName());
|
||||
long times = System.currentTimeMillis() - startTime;
|
||||
log.setTime(times);
|
||||
// 任务状态 0:成功 1:失败
|
||||
log.setIsSuccess(false);
|
||||
log.setExceptionDetail(ThrowableUtil.getStackTrace(e));
|
||||
// 任务如果失败了则暂停
|
||||
if(quartzJob.getPauseAfterFailure() != null && quartzJob.getPauseAfterFailure()){
|
||||
quartzJob.setIsPause(false);
|
||||
//更新状态
|
||||
quartzJobService.updateIsPause(quartzJob);
|
||||
}
|
||||
if(quartzJob.getEmail() != null){
|
||||
EmailService emailService = SpringContextHolder.getBean(EmailService.class);
|
||||
// 邮箱报警
|
||||
if(StringUtils.isNoneBlank(quartzJob.getEmail())){
|
||||
EmailVo emailVo = taskAlarm(quartzJob, ThrowableUtil.getStackTrace(e));
|
||||
emailService.send(emailVo, emailService.find());
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
quartzLogRepository.save(log);
|
||||
}
|
||||
}
|
||||
|
||||
private EmailVo taskAlarm(QuartzJob quartzJob, String msg) {
|
||||
EmailVo emailVo = new EmailVo();
|
||||
emailVo.setSubject("定时任务【"+ quartzJob.getJobName() +"】执行失败,请尽快处理!");
|
||||
Map<String, Object> data = new HashMap<>(16);
|
||||
data.put("task", quartzJob);
|
||||
data.put("msg", msg);
|
||||
TemplateEngine engine = TemplateUtil.createEngine(new TemplateConfig("template", TemplateConfig.ResourceMode.CLASSPATH));
|
||||
Template template = engine.getTemplate("email/taskAlarm.ftl");
|
||||
emailVo.setContent(template.render(data));
|
||||
List<String> emails = Arrays.asList(quartzJob.getEmail().split("[,,]"));
|
||||
emailVo.setTos(emails);
|
||||
return emailVo;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
/*
|
||||
* Copyright 2019-2020 Zheng Jie
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package me.zhengjie.modules.quartz.utils;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import me.zhengjie.exception.BadRequestException;
|
||||
import me.zhengjie.modules.quartz.domain.QuartzJob;
|
||||
import org.quartz.*;
|
||||
import org.quartz.impl.triggers.CronTriggerImpl;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
import javax.annotation.Resource;
|
||||
import java.util.Date;
|
||||
import static org.quartz.TriggerBuilder.newTrigger;
|
||||
|
||||
/**
|
||||
* @author Zheng Jie
|
||||
* @date 2019-01-07
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
public class QuartzManage {
|
||||
|
||||
private static final String JOB_NAME = "TASK_";
|
||||
|
||||
@Resource
|
||||
private Scheduler scheduler;
|
||||
|
||||
public void addJob(QuartzJob quartzJob){
|
||||
try {
|
||||
// 构建job信息
|
||||
JobDetail jobDetail = JobBuilder.newJob(ExecutionJob.class).
|
||||
withIdentity(JOB_NAME + quartzJob.getId()).build();
|
||||
|
||||
//通过触发器名和cron 表达式创建 Trigger
|
||||
Trigger cronTrigger = newTrigger()
|
||||
.withIdentity(JOB_NAME + quartzJob.getId())
|
||||
.startNow()
|
||||
.withSchedule(CronScheduleBuilder.cronSchedule(quartzJob.getCronExpression()))
|
||||
.build();
|
||||
|
||||
cronTrigger.getJobDataMap().put(QuartzJob.JOB_KEY, quartzJob);
|
||||
|
||||
//重置启动时间
|
||||
((CronTriggerImpl)cronTrigger).setStartTime(new Date());
|
||||
|
||||
//执行定时任务
|
||||
scheduler.scheduleJob(jobDetail,cronTrigger);
|
||||
|
||||
// 暂停任务
|
||||
if (quartzJob.getIsPause()) {
|
||||
pauseJob(quartzJob);
|
||||
}
|
||||
} catch (Exception e){
|
||||
log.error("创建定时任务失败", e);
|
||||
throw new BadRequestException("创建定时任务失败");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新job cron表达式
|
||||
* @param quartzJob /
|
||||
*/
|
||||
public void updateJobCron(QuartzJob quartzJob){
|
||||
try {
|
||||
TriggerKey triggerKey = TriggerKey.triggerKey(JOB_NAME + quartzJob.getId());
|
||||
CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
|
||||
// 如果不存在则创建一个定时任务
|
||||
if(trigger == null){
|
||||
addJob(quartzJob);
|
||||
trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
|
||||
}
|
||||
CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(quartzJob.getCronExpression());
|
||||
trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();
|
||||
//重置启动时间
|
||||
((CronTriggerImpl)trigger).setStartTime(new Date());
|
||||
trigger.getJobDataMap().put(QuartzJob.JOB_KEY,quartzJob);
|
||||
|
||||
scheduler.rescheduleJob(triggerKey, trigger);
|
||||
// 暂停任务
|
||||
if (quartzJob.getIsPause()) {
|
||||
pauseJob(quartzJob);
|
||||
}
|
||||
} catch (Exception e){
|
||||
log.error("更新定时任务失败", e);
|
||||
throw new BadRequestException("更新定时任务失败");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除一个job
|
||||
* @param quartzJob /
|
||||
*/
|
||||
public void deleteJob(QuartzJob quartzJob){
|
||||
try {
|
||||
JobKey jobKey = JobKey.jobKey(JOB_NAME + quartzJob.getId());
|
||||
scheduler.pauseJob(jobKey);
|
||||
scheduler.deleteJob(jobKey);
|
||||
} catch (Exception e){
|
||||
log.error("删除定时任务失败", e);
|
||||
throw new BadRequestException("删除定时任务失败");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 恢复一个job
|
||||
* @param quartzJob /
|
||||
*/
|
||||
public void resumeJob(QuartzJob quartzJob){
|
||||
try {
|
||||
TriggerKey triggerKey = TriggerKey.triggerKey(JOB_NAME + quartzJob.getId());
|
||||
CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
|
||||
// 如果不存在则创建一个定时任务
|
||||
if(trigger == null) {
|
||||
addJob(quartzJob);
|
||||
}
|
||||
JobKey jobKey = JobKey.jobKey(JOB_NAME + quartzJob.getId());
|
||||
scheduler.resumeJob(jobKey);
|
||||
} catch (Exception e){
|
||||
log.error("恢复定时任务失败", e);
|
||||
throw new BadRequestException("恢复定时任务失败");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 立即执行job
|
||||
* @param quartzJob /
|
||||
*/
|
||||
public void runJobNow(QuartzJob quartzJob){
|
||||
try {
|
||||
TriggerKey triggerKey = TriggerKey.triggerKey(JOB_NAME + quartzJob.getId());
|
||||
CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
|
||||
// 如果不存在则创建一个定时任务
|
||||
if(trigger == null) {
|
||||
addJob(quartzJob);
|
||||
}
|
||||
JobDataMap dataMap = new JobDataMap();
|
||||
dataMap.put(QuartzJob.JOB_KEY, quartzJob);
|
||||
JobKey jobKey = JobKey.jobKey(JOB_NAME + quartzJob.getId());
|
||||
scheduler.triggerJob(jobKey,dataMap);
|
||||
} catch (Exception e){
|
||||
log.error("定时任务执行失败", e);
|
||||
throw new BadRequestException("定时任务执行失败");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 暂停一个job
|
||||
* @param quartzJob /
|
||||
*/
|
||||
public void pauseJob(QuartzJob quartzJob){
|
||||
try {
|
||||
JobKey jobKey = JobKey.jobKey(JOB_NAME + quartzJob.getId());
|
||||
scheduler.pauseJob(jobKey);
|
||||
} catch (Exception e){
|
||||
log.error("定时任务暂停失败", e);
|
||||
throw new BadRequestException("定时任务暂停失败");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
/*
|
||||
* Copyright 2019-2020 Zheng Jie
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package me.zhengjie.modules.quartz.utils;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import me.zhengjie.utils.SpringContextHolder;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.util.ReflectionUtils;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.concurrent.Callable;
|
||||
|
||||
/**
|
||||
* 执行定时任务
|
||||
* @author /
|
||||
*/
|
||||
@Slf4j
|
||||
public class QuartzRunnable implements Callable<Object> {
|
||||
|
||||
private final Object target;
|
||||
private final Method method;
|
||||
private final String params;
|
||||
|
||||
QuartzRunnable(String beanName, String methodName, String params)
|
||||
throws NoSuchMethodException, SecurityException {
|
||||
this.target = SpringContextHolder.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
|
||||
@SuppressWarnings("all")
|
||||
public Object call() throws Exception {
|
||||
ReflectionUtils.makeAccessible(method);
|
||||
if (StringUtils.isNotBlank(params)) {
|
||||
method.invoke(target, params);
|
||||
} else {
|
||||
method.invoke(target);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user