首页 > 代码库 > spring定时器的用法
spring定时器的用法
quartz.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd">
<!-- 配置Job Bean -->
<bean id="myJob2" class="com.baidu.entity.MyJob2"></bean>
<!-- 配置JobDetail -->
<bean id="job" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject" ref="myJob2"></property>
<property name="targetMethod" value="http://www.mamicode.com/execute"></property>
</bean>
<!-- 配置CronTrigger -->
<bean id="trigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="jobDetail" ref="job"></property>
<property name="cronExpression" value="http://www.mamicode.com/0/3 * * 11 11 ? 2016"></property>
<!-- cron表达式 秒 分钟 小时 日 月 星期 年 *表示匹配所有 ?占位符,只能在日期或星期上使用,无意义 -->
</bean>
<!-- 配置Scheduler -->
<bean id="scheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<!-- 加入Trigger -->
<property name="triggers">
<array>
<ref bean="trigger"/>
</array>
</property>
<!-- 配置quartz的原生属性 -->
<property name="quartzProperties">
<props>
<prop key="org.quartz.threadPool.threadCount">5</prop>
</props>
</property>
<!-- 配置IOC容器启动多长时间以后,quartz开始执行 -->
<property name="startupDelay" value="http://www.mamicode.com/10"></property>
</bean>
</beans>
Job Bean
package com.baidu.entity;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.quartz.JobExecutionException;
public class MyJob2{
public void execute() throws JobExecutionException {
String date = new SimpleDateFormat("HH:mm:ss").format(new Date());
System.out.println("do my job at "+date);
}
}
需要的jar包
<!-- 定时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>
spring定时器的用法