一 使用注解Task
1、在applicationContext.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:context="http://www.springframework.org/schema/context" xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.2.xsd "> <!-- 扫描路径--> <context:component-scan base-package="com.mediaforce.news.api.quartz" /> <task:executor id="executor" pool-size="1" /> <task:scheduler id="scheduler" pool-size="1" /> <task:annotation-driven executor="executor" scheduler="scheduler" /> </beans>
2、在任务类中使用注解
import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component(“taskJob”) public class TaskJob { @Scheduled(cron = "0 0 3 * * ?") public void job1() { System.out.println(“任务进行中。。。”); } }
二、使用xml配置quarz
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd "> <!-- 微信抓取 --> <bean id="weixinJobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <property name="targetObject"> <ref bean="taskJob" /> //目标类 </property> <property name="targetMethod"> <value>weixin</value> //目标执行方法 </property> </bean> <!-- 微信抓取,1分钟一次 --> <bean id="cronWeixinJobDetail" class="org.springframework.scheduling.quartz.CronTriggerBean"> <property name="jobDetail"> <ref bean="weixinJobDetail" /> </property> <property name="cronExpression"> <value>0 0/1 * * * ?</value> </property> </bean> <!-- 执行定时任务--> <bean id="zz" autowire="no" class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> <property name="triggers"> <list> <ref bean="cronWeixinJobDetail" /> </list> </property> </bean> </beans>