java善假于物(三):quartz定时器融合spring

前言

在spring的项目开发中,我们经常会用到定时器,虽然java本身提供了定时器,但是我为大家推荐一个更强的的作业调度框架:quartz,接下来教大家怎么利用spring全程注解的方式配置quartz

开源地址:https://github.com/bigbeef
个人博客:http://blog.cppba.com

maven配置

1
2
3
4
5
6
<!--quartz定时器-->
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.2.3</version>
</dependency>

spring的注解配置文件QuartzConfiguration.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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;
}
}

测试任务LoseClassQuartz.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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);
}
}

运行结果:

运行成功!