1.如果是web工程,web.xml需要配置监听器:
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
2.applicationContext.xml配置:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:task="http://www.springframework.org/schema/task" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/fex http://www.springframework.org/schema/fex/spring-fex-1.5.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd"> <!-- Enables the Spring Task @Scheduled programming model --> <context:component-scan base-package="*" /> <task:executor id="executor" pool-size="5" /> <task:scheduler id="scheduler" pool-size="10" /> <task:annotation-driven executor="executor" scheduler="scheduler" /> </beans>
3.加载quartz jar包
4.Job类
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component public class Job { @Autowired BuildService buildService; /** * 定时一小时执行一次 * */ @Scheduled(cron="0 0 */1 * * *") public void buildOnTimer(){ buildService.buildOnTimer(); } @Scheduled(cron="*/10 * * * * *") public void s10(){ System.out.println("10s"); } @Scheduled(cron="0 */1 * * * *") public void m1(){ System.out.println("1m"); } @Scheduled(cron="0 0 */1 * * *") public void h1(){ System.out.println("1h"); } }
这样就简单搞定了