欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

springboot动态定时任务的实现方法示例

程序员文章站 2022-03-29 22:58:45
1、maven引入quartz包

1、maven引入quartz包

<!-- https://mvnrepository.com/artifact/org.quartz-scheduler/quartz -->
<dependency>
 <groupid>org.quartz-scheduler</groupid>
 <artifactid>quartz</artifactid>
 <version>2.3.2</version>
</dependency>

2、创建定时任务工厂类

/**
 * 定时任务工厂类
 */
@component
public class jobfactory extends springbeanjobfactory implements applicationcontextaware {

 private transient autowirecapablebeanfactory beanfactory;

 @override
 protected object createjobinstance(triggerfiredbundle bundle) throws exception {
 final object jobinstance = super.createjobinstance(bundle);
 beanfactory.autowirebean(jobinstance);
 return jobinstance;
 }

 @override
 public void setapplicationcontext(applicationcontext applicationcontext) throws beansexception {
 this.beanfactory = applicationcontext.getautowirecapablebeanfactory();
 }

}

3、创建定时任务抽象类

public abstract class abstracttask implements job {

 private logger logger = loggerfactory.getlogger(abstracttask.class);

 protected abstract void executeinternal(jobexecutioncontext context) throws exception;

 /**
 * 定时任务标识
 */
 private string key;

 /**
 * 数据库里配置的主键id
 */
 private long databaseid;

 @override
 public void execute(jobexecutioncontext context) {
 try {
  executeinternal(context);
 } catch (exception e) {
  logger.error(e.getmessage(), e);
  logger.error("job execute failed!");
 }
 }

 public string getkey() {
 return key;
 }

 public void setkey(string key) {
 this.key = key;
 }

 public long getdatabaseid() {
 return databaseid;
 }

 public void setdatabaseid(long databaseid) {
 this.databaseid = databaseid;
 }
}

4、创建定时任务业务实现类

这里可以写你的业务代码,实现具体的业务逻辑。

@component("jobtask")
public class jobtask extends abstracttask {

 @override
 protected void executeinternal(jobexecutioncontext context) {
 system.out.println("key = " + this.getkey());
 system.out.println("databaseid = " + this.getdatabaseid());
 }

}

5、创建定时任务管理器

包括项目启动时添加定时任务,手动添加定时任务,更新定时任务,删除定时任务方法。

/**
 * 定时任务管理容器 component (单例模式)
 */
@component
@scope("singleton")
public class jobquartzmanager implements applicationcontextaware {

 /**
 * 创建新的scheduler
 */
 private static schedulerfactory schedulerfactory = new stdschedulerfactory();

 private scheduler scheduler;

 /**
 * 定义组名称,不同的组用于区分任务
 */
 private static final string job_group_name = "job_group_name";

 private static final string trigger_group_name = "trigger_group_name";

 /**
 * 日志
 */
 private logger logger = loggerfactory.getlogger(jobquartzmanager.class);

 private applicationcontext applicationcontext;

 @autowired
 private jobfactory jobfactory;

 public void start() {
 //启动定时任务(初始化)
 try {
  this.scheduler = schedulerfactory.getscheduler();
  scheduler.setjobfactory(jobfactory); //设置定时任务工厂模式
  //项目启动时默认给spring容器添加动态的定时任务
  this.addjob("job" + 100l, 100l, jobtask.class, "0/2 * * * * ?");
 } catch (schedulerexception e) {
  logger.error(e.getmessage(), e);
  throw new runtimeexception("init scheduler failed");
 }
 }

 public boolean addjob(string jobname, long databaseid, class jobclass, string cronexp) {
 boolean result = false;
 if (!cronexpression.isvalidexpression(cronexp)) {
  logger.error("illegal cron expression format({})", cronexp);
  return result;
 }
 try {
  jobdetail jobdetail = jobbuilder.newjob().withidentity(new jobkey(jobname, job_group_name))
   .oftype((class<abstracttask>) class.forname(jobclass.getname()))
   .build();
  //创建完jobdetail之后,使用语句传参数值,方便定时任务内部识别它是什么标识
  jobdatamap jobdatamap = jobdetail.getjobdatamap();
  jobdatamap.put("key", jobname);
  jobdatamap.put("databaseid", databaseid);
  trigger trigger = triggerbuilder.newtrigger()
   .forjob(jobdetail)
   .withschedule(cronschedulebuilder.cronschedule(cronexp))
   .withidentity(new triggerkey(jobname, trigger_group_name))
   .build();
  scheduler.schedulejob(jobdetail, trigger);
  scheduler.start();
  result = true;
 } catch (exception e) {
  logger.error(e.getmessage(), e);
  logger.error("quartzmanager add job failed");
 }
 return result;
 }

 public boolean updatejob(string jobname, string cronexp) {
 boolean result = false;
 if (!cronexpression.isvalidexpression(cronexp)) {
  logger.error("illegal cron expression format({})", cronexp);
  return result;
 }
 jobkey jobkey = new jobkey(jobname, job_group_name);
 triggerkey triggerkey = new triggerkey(jobname, trigger_group_name);
 try {
  if (scheduler.checkexists(jobkey) && scheduler.checkexists(triggerkey)) {
  jobdetail jobdetail = scheduler.getjobdetail(jobkey);
  trigger newtrigger = triggerbuilder.newtrigger()
   .forjob(jobdetail)
   .withschedule(cronschedulebuilder.cronschedule(cronexp))
   .withidentity(new triggerkey(jobname, trigger_group_name))
   .build();
  scheduler.reschedulejob(triggerkey, newtrigger);
  result = true;
  } else {
  logger.error("update job name:{},group name:{} or trigger name:{},group name:{} not exists..",
   jobkey.getname(), jobkey.getgroup(), triggerkey.getname(), triggerkey.getgroup());
  }
 } catch (schedulerexception e) {
  logger.error(e.getmessage(), e);
  logger.error("update job name:{},group name:{} failed!", jobkey.getname(), jobkey.getgroup());
 }
 return result;
 }

 public boolean deletejob(string jobname) {
 boolean result = false;
 jobkey jobkey = new jobkey(jobname, job_group_name);
 try {
  if (scheduler.checkexists(jobkey)) {
  result = scheduler.deletejob(jobkey);
  } else {
  logger.error("delete job name:{},group name:{} not exists.", jobkey.getname(), jobkey.getgroup());
  }
 } catch (schedulerexception e) {
  logger.error(e.getmessage(), e);
  logger.error("delete job name:{},group name:{} failed!", jobkey.getname(), jobkey.getgroup());
 }
 return result;
 }

 @override
 public void setapplicationcontext(applicationcontext applicationcontext) throws beansexception {
 this.applicationcontext = applicationcontext;
 }

}

6、创建定时任务启动类

项目运行时给spring注入定时任务

/**
 * 定时任务启动类
 */
@component
public class jobrunner implements applicationrunner {

 //注入定时任务管理器
 @autowired
 private jobquartzmanager quartzmanager;

 /**
 * 项目启动时激活定时任务
 */
 @override
 public void run(applicationarguments applicationarguments) {
 system.out.println("--------------------注入定时任务---------------------");
 quartzmanager.start();
 system.out.println("--------------------定时任务注入完成---------------------");
 }

}

7、测试案例

@restcontroller
@requestmapping("/job")
public class jobcontroller {

 @autowired
 jobquartzmanager quartzmanager;

 @postmapping("addjob")
 @responsebody
 public string addjob(@requestparam("databaseid") long databaseid, @requestparam("cronexp") string cronexp){
 boolean success = quartzmanager.addjob("job" + databaseid, databaseid, jobtask.class, cronexp);
 if(success){
  return "添加成功";
 }else{
  return "添加失败!";
 }
 }

 @postmapping("deletejob")
 @responsebody
 public string deletejob(@requestparam("jobname") string jobname){
 boolean success = quartzmanager.deletejob(jobname);
 if(success){
  return "删除成功";
 }else{
  return "删除失败!";
 }
 }

 @postmapping("updatejob")
 @responsebody
 public string updatejob(@requestparam("jobname") string jobname, @requestparam("cronexp") string cronexp){
 boolean success = quartzmanager.updatejob(jobname, cronexp);
 if(success){
  return "更新成功";
 }else{
  return "更新失败!";
 }
 }

}

总结

到此这篇关于springboot实现动态定时任务的文章就介绍到这了,更多相关springboot动态定时任务内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!