SpringBoot整合定时任务
作者Gitee地址 https://gitee.com/thciweicloud作者项目 面包博客,一个微服务架构的前后端分离博客系统。定时任务主流 quartz定时任务我们需要了解一下cron表达式启动类添加@EnableScheduling配置类bean.setTriggers有几个trigger(触发器)写几个即可simpleTriggerFactoryBean最简单cronTriggerF
·
作者Gitee地址 https://gitee.com/thciweicloud
作者项目 面包博客,一个微服务架构的前后端分离博客系统。
定时任务
主流 quartz
定时任务我们需要了解一下cron表达式
启动类添加@EnableScheduling
- 配置类
bean.setTriggers有几个trigger(触发器)写几个即可
simpleTriggerFactoryBean最简单
cronTriggerFactoryBean最灵活
package com.thciwei.demo.config;
import com.thciwei.demo.job.MySecondJob;
import org.quartz.JobDataMap;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.*;
import java.util.Date;
@Configuration
public class QuartzConfig {
@Bean
MethodInvokingJobDetailFactoryBean methodInvokingJobDetailFactoryBean() {
MethodInvokingJobDetailFactoryBean bean = new MethodInvokingJobDetailFactoryBean();
bean.setTargetBeanName("myFirstJob");
bean.setTargetMethod("sayHello");
return bean;
}
@Bean
JobDetailFactoryBean jobDetailFactoryBean() {
JobDetailFactoryBean bean = new JobDetailFactoryBean();
JobDataMap map = new JobDataMap();
map.put("name", "thciwei");
bean.setJobDataAsMap(map);
bean.setJobClass(MySecondJob.class);
return bean;
}
@Bean
SimpleTriggerFactoryBean simpleTriggerFactoryBean() {
SimpleTriggerFactoryBean bean = new SimpleTriggerFactoryBean();
bean.setJobDetail(methodInvokingJobDetailFactoryBean().getObject());
bean.setStartTime(new Date());
bean.setRepeatInterval(2000);
//循环
bean.setRepeatCount(3);
return bean;
}
@Bean
CronTriggerFactoryBean cronTriggerFactoryBean() {
CronTriggerFactoryBean bean = new CronTriggerFactoryBean();
bean.setJobDetail(jobDetailFactoryBean().getObject());
bean.setCronExpression("* * * * * ?");
return bean;
}
@Bean
SchedulerFactoryBean schedulerFactoryBean() {
SchedulerFactoryBean bean = new SchedulerFactoryBean();
bean.setTriggers(simpleTriggerFactoryBean().getObject(),cronTriggerFactoryBean().getObject());
return bean;
}
}
- MyFirstJob
package com.thciwei.demo.job;
import org.springframework.stereotype.Component;
import java.util.Date;
@Component
public class MyFirstJob {
public void sayHello() {
System.out.println("first job say hello"+new Date());
}
}
- MySecondJob
需要继承QuartzJobBean
package com.thciwei.demo.job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;
import java.util.Date;
public class MySecondJob extends QuartzJobBean {
private String name;
public void setName(String name){
this.name=name;
}
@Override
protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
System.out.println("second job say hello:"+name+":"+new Date());
}
}
开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!
更多推荐
已为社区贡献1条内容
所有评论(0)