pom
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.2.1</version>
</dependency>
1 先配置一个jobFactory类 extends 继承AdaptableJobFactory
@Component("jobFactory")
public class MyJobFactory extends AdaptableJobFactory {
@Autowired
private AutowireCapableBeanFactory autowireCapableBeanFactory;
@Override
protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
// TODO Auto-generated method stub
Object jobInstance = super.createJobInstance(bundle);
autowireCapableBeanFactory.autowireBean(jobInstance);
return jobInstance;
}
2.创建quartz配置类
package test.conntroller.quaytz;
import org.quartz.spi.JobFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
import org.springframework.scheduling.quartz.JobDetailFactoryBean;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
@Configuration
public class quzrtzConfig {
/**
* 1.创建Job对象
*/
@Bean
public JobDetailFactoryBean getJobDetailFactoryBean(){
JobDetailFactoryBean factory = new JobDetailFactoryBean();
//把我们需要定时的类放进来,MyJob就是我们自定义的定时类
factory.setJobClass(MyJob.class);
return factory;
}
/**
* 2.创建Trigger
*/
/*@Bean
public SimpleTriggerFactoryBean getSimpleTriggerFactoryBean(JobDetailFactoryBean jobDetailFactoryBean){
SimpleTriggerFactoryBean factory = new SimpleTriggerFactoryBean();
//关联JobDetail对象
factory.setJobDetail(jobDetailFactoryBean.getObject());
//重复间隔时间(毫秒为单位)
factory.setRepeatInterval(5000);
//重复次数
factory.setRepeatCount(4);
return factory;
}*/
@Bean
public CronTriggerFactoryBean getSimpleTriggerFactoryBean(JobDetailFactoryBean jobDetailFactoryBean){
CronTriggerFactoryBean factory = new CronTriggerFactoryBean();
//关联JobDetail对象
factory.setJobDetail(jobDetailFactoryBean.getObject());
//时间
factory.setCronExpression("0/3 * * * * ?");
return factory;
}
/**
* 3.创建Scheduler对象
*/
@Bean
public SchedulerFactoryBean getSchedulerFactoryBean(CronTriggerFactoryBean triggerFactoryBean,JobFactory jobFactory){
SchedulerFactoryBean factory = new SchedulerFactoryBean();
//关联trigger
factory.setTriggers(triggerFactoryBean.getObject());
//重新JobFactory
factory.setJobFactory(jobFactory);
return factory;
}
}
3.创建Myjob类 implements 实现Job的execute
exceute里就是我们定时执行的代码
public class MyJob implements Job{
public void execute(JobExecutionContext context) throws JobExecutionException {
//System.out.println(new Date()+"1111111");
}
}