Spring Boot有很多定时任务,这里介绍一下在Spring Boot中如何使用quartz框架
- 首先在pom.xml里添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
- 在主文件夹下添加工厂类SpringJobFactory
import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.scheduling.quartz.AdaptableJobFactory;
import org.springframework.stereotype.Component;
@Component
public class SpringJobFactory extends AdaptableJobFactory {
@Autowired
private AutowireCapableBeanFactory capableBeanFactory;
@Override
protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
Object jobInstance = super.createJobInstance(bundle);
capableBeanFactory.autowireBean(jobInstance);
return jobInstance;
}
}
- 然后新建一个配置类QuartzConfig
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
@Configuration
public class QuartzConfig {
@Autowired
private SpringJobFactory springJobFactory;
@Bean
public SchedulerFactoryBean schedulerFactoryBean() {
SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
schedulerFactoryBean.setJobFactory(springJobFactory);
return schedulerFactoryBean;
}
@Bean
public Scheduler scheduler() {
return schedulerFactoryBean().getScheduler();
}
}
- 最后新建一个任务配置类即可
(我这里给的列子是每天23:59:59向数据库插入数据)
import com.example.springbootquartz.dao.AthletesRepository;
import com.example.springbootquartz.dao.WalksRepository;
import com.example.springbootquartz.entity.Athletes;
import com.example.springbootquartz.entity.Walks;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.List;
import java.util.Random;
@Component
public class WalksJob {
@Resource
private AthletesRepository athletesRepository;
@Scheduled(cron = "59 59 23 * * ? ")
public void updateTodayWalks() throws Exception {
List<Athletes> athletes = athletesRepository.findAll();
for (int i = 0; i < athletes.size(); i++) {
List<Walks> walks = athletes.get(i).getWalksList();
walks.add(new Walks((long) new Random().nextInt(100000), LocalDate.now().toString()));
athletesRepository.save(athletes.get(i));
}
}
}
- github地址:传送门
网友评论