作者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());
}
}