文章目录
介绍
平时在工作中经常会用到定时任务,如自动实现计费,扫描订单,清理日志,数据定时抽取等等。本篇将介绍springboot整合quartz实现定时任务以及springboot自带的定时任务。
springboot的定时任务
启动类
/**
* 启动类
*/
@SpringBootApplication
//@EnableScheduling
public class SpringbootQuartzApplication {
public static void main( String[] args )
{
SpringApplication.run(SpringbootQuartzApplication.class,args);
}
}
定时任务类
@EnableScheduling 开启注解,以及@Scheduled 配置定时任务执行的时间即可。
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import java.text.SimpleDateFormat;
import java.util.Date;
@Configuration
@EnableScheduling
public class SimpleSchedule {
//每五秒执行一次
@Scheduled(cron="*/5 * * * * ?")
public void schedule(){
System.out.println("执行定时任务..."+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
}
}
quartz定时任务
依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
<dependency>
实体类
创表语句:
-- quartz.sys_job definition
CREATE TABLE `sys_job` (
`job_id` int NOT NULL AUTO_INCREMENT,
`job_class` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL COMMENT '任务类名',
`job_cron` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL COMMENT 'cron表达式',
`job_params` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL COMMENT '参数',
`job_desc` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL COMMENT '描述',
`job_status` int DEFAULT NULL COMMENT '状态 1正常 0停止',
`create_by` varchar(32) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL COMMENT '创建人',
`create_time` datetime DEFAULT NULL COMMENT '创建时间',
`del_flag` int DEFAULT NULL COMMENT '删除状态',
`update_by` varchar(32) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL COMMENT '修改人',
`update_time` datetime DEFAULT NULL COMMENT '修改时间',
PRIMARY KEY (`job_id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
实体类
@Data
@TableName("`sys_job`")
public class SysJob implements Serializable {
@TableId(value = "job_id",type = IdType.AUTO )
private Integer jobId;
//任务类
@TableField(value = "job_class")
private String jobClass;
//定时任务表达式
@TableField(value = "job_cron")
private String jobCron;
//任务参数
@TableField(value = "job_params")
private String jobParams;
//任务描述
@TableField(value = "job_desc")
private String jobDesc;
//任务状态 1 正常 0 停止
private String jobStatus;
//是否逻辑删除
@TableLogic
@TableField(value = "del_flag")
private String delFlag;
//创建人
@TableField(value = "create_by")
private String createBy;
//创建时间
@JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@TableField(value = "create_time",fill = FieldFill.INSERT)
private String createTime;
//更新人
@TableField(value = "update_by")
private String updateBy;
//更新时间
@JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@TableField(value = "update_time",fill = FieldFill.INSERT_UPDATE)
private String updateTime;
}
对于任务进行CRUD操作
mapper映射
/**
* 系统任务映射类
*/
@Mapper
public interface SysJobMapper extends BaseMapper<SysJob> {
}
服务类
/**
* <p>
* 系统任务服务类 实现任务的增删改查
* </p>
*/
public interface ISysJobService extends IService<SysJob> {
//添加任务
void saveSysJob(SysJob job);
//更新任务
void updateSysJob(SysJob job);
//删除任务
void delSysJob(SysJob job);
//启动任务
void restartSysJob(SysJob job);
//停止任务
void stopSysJob(SysJob job);
}
服务实现类
/**
* <p>
* 任务表 服务实现类
* </p>
*/
@Service
public class SysJobServiceImpl extends ServiceImpl<SysJobMapper, SysJob> implements ISysJobService {
@Autowired
BaseMapper baseMapper;
@Autowired
private Scheduler scheduler;
//添加任务
@Override
public void saveSysJob(SysJob job){
//根据状态是否加入定时任务
if("1".equals(job.getJobStatus())){
// 定时器添加
this.addSysJob(job.getJobClass().trim(), job.getJobCron().trim(), job.getJobParams());
}
//保存数据库
baseMapper.insert(job);
}
//更新任务
@Override
public void updateSysJob(SysJob job){
//根据状态是否加入定时任务
if("1".equals(job.getJobStatus())){
// 定时器添加
this.addSysJob(job.getJobClass().trim(), job.getJobCron().trim(), job.getJobParams());
}else{
//停止定时任务
this.stopSysJob(job);
}
//保存数据库
baseMapper.updateById(job);
}
//删除任务
@Override
public void delSysJob(SysJob job){
this.stopSysJob(job);
//数据库删除
baseMapper.deleteById(job.getJobId());
}
//启动任务
@Override
public void restartSysJob(SysJob job){
//先停止
this.stopSysJob(job);
//在添加任务
this.addSysJob(job.getJobClass(),job.getJobCron(),job.getJobParams());
}
//停止任务
@Override
public void stopSysJob(SysJob job){
try {
String jobClassName = job.getJobClass();
//删除触发器
scheduler.pauseTrigger(TriggerKey.triggerKey(jobClassName));
scheduler.unscheduleJob(TriggerKey.triggerKey(jobClassName));
scheduler.deleteJob(JobKey.jobKey(jobClassName));
} catch (Exception e) {
e.printStackTrace();
}
//更新任务状态
this.updateSysJob(job);
}
/**
* 添加定时任务
* */
private void addSysJob(String jobClassName, String cronExpression, String parameter) {
try {
// 启动调度器
scheduler.start();
// 构建job信息
JobDetail jobDetail = JobBuilder.newJob(getClass(jobClassName).getClass()).withIdentity(jobClassName).usingJobData("parameter", parameter).build();
// 表达式调度构建器(即任务执行的时间)
CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cronExpression);
// 按新的cronExpression表达式构建一个新的trigger
CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(jobClassName).withSchedule(scheduleBuilder).build();
scheduler.scheduleJob(jobDetail, trigger);
} catch(Exception e) {
e.printStackTrace();
}
}
private static Job getClass(String classname) throws Exception {
Class<?> class1 = Class.forName(classname);
return (Job) class1.newInstance();
}
}
简单的任务
public class SysJob1 implements Job {
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
System.out.println("执行定时任务SysJob1..."+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
}
}
public class SysJob2 implements Job {
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
System.out.println("执行定时任务SysJob2..."+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
}
}
controller
@RestController
public class SysJobController {
@Autowired
ISysJobService sysJobService;
//添加任务
@GetMapping("/saveSysJob")
void saveSysJob(){
SysJob sysJob = new SysJob();
sysJob.setJobClass("com.elite.springboot.task.SysJob2");
sysJob.setJobCron("*/2 * * * * ?");
sysJob.setJobParams("");
sysJob.setJobDesc("2秒中一次定时执行任务sysjob2");
sysJob.setJobStatus("1"); //正常
sysJobService.saveSysJob(sysJob);
}
//更新任务
@GetMapping("/updateSysJob")
void updateSysJob(){
SysJob sysJob = new SysJob();
sysJob.setJobId(1);
sysJob.setJobClass("com.elite.springboot.task.SysJob1");
sysJob.setJobCron("*/3 * * * * ?");
sysJob.setJobParams("");
sysJob.setJobDesc("2秒中一次定时执行任务sysjob1");
sysJob.setJobStatus("1"); //正常
sysJobService.updateSysJob(sysJob);
}
}