前言
在spring的项目开发中,我们经常会用到定时器,虽然java本身提供了定时器,但是我为大家推荐一个更强的的作业调度框架:quartz,接下来教大家怎么利用spring全程注解的方式配置quartz
1.maven配置
<!--quartz定时器-->
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.2.3</version>
</dependency>
2.spring的注解配置文件QuartzConfiguration.java
package com.qingcheng.club.configuration;
import com.qingcheng.club.quartz.LoseClassQuartz;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
import org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
@Configuration
public class QuartzConfiguration {
@Autowired
private LoseClassQuartz loseClassQuartz;
@Bean
public MethodInvokingJobDetailFactoryBean jobDetail(){
MethodInvokingJobDetailFactoryBean methodInvokingJobDetailFactoryBean = new MethodInvokingJobDetailFactoryBean();
methodInvokingJobDetailFactoryBean.setTargetObject(loseClassQuartz);
methodInvokingJobDetailFactoryBean.setTargetMethod("doJob");
return methodInvokingJobDetailFactoryBean;
}
@Bean
public CronTriggerFactoryBean cronTriggerBean(){
CronTriggerFactoryBean cronTriggerFactoryBean = new CronTriggerFactoryBean();
cronTriggerFactoryBean.setJobDetail(jobDetail().getObject());
//每5秒执行一次
//cronTriggerFactoryBean.setCronExpression("0/5 * * * * ?");
//每秒执行一次,这个表达式很重要,任务调度执行频率
cronTriggerFactoryBean.setCronExpression("* * * * * ?");
return cronTriggerFactoryBean;
}
@Bean
public SchedulerFactoryBean trigger(){
SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
schedulerFactoryBean.setTriggers(cronTriggerBean().getObject());
return schedulerFactoryBean;
}
}
3.测试任务LoseClassQuartz.java
package com.qingcheng.club.quartz;
import com.qingcheng.service.BookService;
import com.qingcheng.util.Globals;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
@Component("LoseClassQuartz")
public class LoseClassQuartz{
private static Logger logger = LoggerFactory.getLogger(LoseClassQuartz.class);
public void doJob(){
SimpleDateFormat sdfyyyyMMddHHmmss = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String now = sdfyyyyMMddHHmmss.format(new Date());
System.out.println("time:"+now);
}
}
4.运行结果:
运行成功!
网友评论