本文实例为大家分享了springBoot+Quartz实现动态定时任务的具体代码,供大家参考,具体内容如下
目前常用的几种任务调度
- Timer,简单无门槛,一般也没人用。
- spring @Scheduled注解,一般集成于项目中,小任务很方便。
- 开源工具 Quartz,分布式集群开源工具,以下两个分布式任务应该都是基于Quartz实现的,可以说是中小型公司必选,当然也视自身需求而定。
- 分布式任务 XXL-JOB,是一个轻量级分布式任务调度框架,支持通过 Web 页面对任务进行 CRUD 操作,支持动态修改任务状态、暂停/恢复任务,以及终止运行中任务,支持在线配置调度任务入参和在线查看调度结果。
- 分布式任务 Elastic-Job,是一个分布式调度解决方案,由两个相互独立的子项目 Elastic-Job-Lite 和 Elastic-Job-Cloud 组成。定位为轻量级无中心化解决方案,使用 jar 包的形式提供分布式任务的协调服务。支持分布式调度协调、弹性扩容缩容、失效转移、错过执行作业重触发、并行调度、自诊。
- 分布式任务 Saturn,Saturn是唯品会在github开源的一款分布式任务调度产品。它是基于当当elastic-job来开发的,其上完善了一些功能和添加了一些新的feature。目前在github上开源大半年,470个star。Saturn的任务可以用多种语言开发比如python、Go、Shell、Java、Php。其在唯品会内部已经发部署350+个节点,每天任务调度4000多万次。同时,管理和统计也是它的亮点。
SpringBoot项目的实现方法
1.config配置
import org.quartz.Scheduler;
import org.quartz.ee.servlet.QuartzInitializerListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import java.io.IOException;
import java.util.Properties;
/**
* quartz配置
*/
@Configuration
public class SchedulerConfig {
@Bean(name="SchedulerFactory")
public SchedulerFactoryBean schedulerFactoryBean() throws IOException {
SchedulerFactoryBean factory = new SchedulerFactoryBean();
factory.setAutoStartup(true);
//factory.setStartupDelay(5);//延时5秒启动
return factory;
}
/*
* quartz初始化监听器
*/
@Bean
public QuartzInitializerListener executorListener() {
return new QuartzInitializerListener();
}
/*
* 通过SchedulerFactoryBean获取Scheduler的实例
*/
@Bean(name="Scheduler")
public Scheduler scheduler() throws IOException {
return schedulerFactoryBean().getScheduler();
}
}
2.实现方法
/**
* 新建任务
* **/
@ApiOperation(value = "Test-add", notes = "Test-add")
@ApiImplicitParams({
@ApiImplicitParam(name = "cruiseId", value = "巡航线id", required = true, paramType = "path"),
@ApiImplicitParam(name = "jobName", value = "任务名称", required = true, paramType = "query"),
@ApiImplicitParam(name = "jobGroup", value = "任务分组", required = true, paramType = "query"),
@ApiImplicitParam(name = "executeDate", value = "当前时间[yyyy-MM-dd HH:mm:ss]", required = true, paramType = "query", dataType = "Date")})
@PutMapping("/test/add/{cruiseId}")
public ResultBody test(@PathVariable("cruiseId") String cruiseId,@RequestParam("jobName") String jobName,@RequestParam("jobGroup") String jobGroup,
@RequestParam(value = "executeDate")@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date executeDate) {
try {
SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//构建job信息
JobDetail job = JobBuilder.newJob(CruisePlanJob.class).withIdentity(jobName, jobGroup)
.withDescription("巡航计划").build();
JobDataMap jobDataMap = job.getJobDataMap();
jobDataMap.put("cruiseId", cruiseId);
//CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule("cron的表达式");
Trigger trigger = TriggerBuilder.newTrigger()
.withIdentity("trigger" + jobName, jobGroup)
.startAt(executeDate)
.withSchedule(SimpleScheduleBuilder.simpleSchedule().withRepeatCount(0))
.build();
//SimpleScheduleBuilder.simpleSchedule().withRepeatCount(0).withIntervalInSeconds(20)//每隔多少秒执行一次; withRepeatCount 设置重复的次数
//.startNow().withSchedule(cronScheduleBuilder)
//交由Scheduler安排触发
scheduler.scheduleJob(job, trigger);
System.out.println("startJob:"+JobKey.jobKey(jobName));
} catch (Exception e) {
e.printStackTrace();
return ResultBody.failed();
}
return ResultBody.ok();
}
/**
* 删除任务
* **/
@ApiOperation(value = "Test-remove", notes = "Test-remove")
@ApiImplicitParams({
@ApiImplicitParam(name = "jobName", value = "任务名称", required = true, paramType = "query"),
@ApiImplicitParam(name = "jobGroup", value = "任务分组", required = true, paramType = "query")})
@GetMapping("/test/remove")
public ResultBody remove(@RequestParam("jobName") String jobName,@RequestParam("jobGroup") String jobGroup) {
try {
TriggerKey triggerKey = TriggerKey.triggerKey(jobName, jobGroup);
// 停止触发器
scheduler.pauseTrigger(triggerKey);
// 移除触发器
scheduler.unscheduleJob(triggerKey);
// 删除任务
boolean result = scheduler.deleteJob(JobKey.jobKey(jobName, jobGroup));
System.out.println(result);
System.out.println("removeJob:"+JobKey.jobKey(jobName));
} catch (Exception e) {
e.printStackTrace();
return ResultBody.failed();
}
return ResultBody.ok();
}
3.CruisePlanJob类实现具体逻辑
@Slf4j
public class CruisePlanJob implements Job {
@Override
public void execute(JobExecutionContext context) {
try{
JobDataMap jdMap = context.getJobDetail().getJobDataMap();
String cruiseId = (String) jdMap.get("cruiseId");
String panId = (String) jdMap.get("panId");
String userId = (String) jdMap.get("userId");
String appId = (String) jdMap.get("appId");
//TODO 逻辑待补充
log.info("cruisePlan-CruisePlanJob-计划执行开始===>panId:{}---cruiseId:{}---appId:{}---userId:{}---resultBody:{}", panId, cruiseId, appId, userId, resultBody);
}catch (Exception e){
e.printStackTrace();
}
}
}
4.另外两种任务的方法
//恢复任务
scheduler.resumeJob(key);
//停止任务
scheduler.pauseJob(key);