spring集成quartz定時器使用

1.由於基於maven項目管理,先在pom文件中添加quartz jar包依賴spring

<!-- quartz -->
		<dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz</artifactId>
            <version>2.2.1</version>
        </dependency>
        <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz-jobs</artifactId>
            <version>2.2.1</version>
        </dependency>

2.在spring的ApplicationContext.xml文件中新增maven

<!-- 系統調度控制器 -->
	<bean id="statTask"
		class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
		<property name="targetObject" ref="emcee_stat" />
		<property name="targetMethod" value="execute" />
		<property name="concurrent" value="false" />
	</bean>
	<bean id="stat_cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
		<property name="jobDetail" ref="statTask" />
		<property name="cronExpression" value="0 04 19 * * ?" />
	</bean>
	
	
	<bean id="LiveTask"
		class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
		<property name="targetObject" ref="live_task" />
		<property name="targetMethod" value="execute" />
		<property name="concurrent" value="false" />
	</bean>
	<bean id="Live_cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
		<property name="jobDetail" ref="LiveTask" />
		<property name="cronExpression" value="0 30 10 * * ?" />
	</bean>
	
	
	
	<bean id="schdulerFactory" lazy-init="false"
		class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
		<property name="triggers">
			<list>
				<ref bean="stat_cronTrigger" />
				<ref bean="Live_cronTrigger" />
			</list>
		</property>
	</bean>

3.對應實現代碼以下,該中方式採用組件註解,注入servicethis

@Component("live_task")
public class AutoSettleLiveTask {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(AutoSettleLiveTask.class);
	
	@Autowired
	private BatchService batchService;
	
	private static AutoSettleLiveTask autoSettleLiveTask; // 靜態初使化 一個AutoSettleLiveTask類
	// 這樣是爲了在spring初使化以前
	
	public void setBatchService(BatchService batchService) {
		this.batchService = batchService;
	}
	
	@PostConstruct // 經過@PostConstruct 和 @PreDestroy 方法 實現初始化和銷燬bean以前進行的操做
	public void init() {
		autoSettleLiveTask = this;
		autoSettleLiveTask.batchService = this.batchService; // 初使化時將已靜態化的batchService實例化
	
	}
	
	@PreDestroy  
	public void destory() {   
	} 
	
	public void execute() throws IllegalArgumentException, IllegalAccessException{
		LOGGER.info("定時任務-begin");
		
		
	}
	
	
}
相關文章
相關標籤/搜索