方式一:Spring+quartz
配置方式如上一篇中提到的,这个是很完整的了,我已经测试过了
http://blog.csdn.net/qq_22585755/article/details/48246675
方式二: Spring + task
先写一个普通类,包括一个方法,将其注册为bean
import java.util.Date;
import org.springframework.stereotype.Component;
/**
*
* @author TongYinLing
*/
@Component("testSchedule")
public class TestSchedule
{
public void task(){
System.out.println("cron!" + new Date().getTime());
}
}
PS:如果在task方法上使用了@Schedule(cron="0/5 * * * * * "),此cron优先于配置xml中的
xml配置为:(由于我本地系统中还需要其他的配置,所以关于task的内容我重点标记出来了)
<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:tx="http://www.springframework.org/schema/tx"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.0.xsd">
<!-- 添加注解驱动 -->
<tx:annotation-driven />
<!-- Spring定时器注解开关-->
<task:annotation-driven />
<!-- 自动扫描的包名 -->
<context:component-scan base-package="*" />
<!-- 开启任务调度 -->
<task:scheduled-tasks>
<task:scheduled ref="testSchedule" method="task" cron="0/13 * * * * ?" />
</task:scheduled-tasks>
</beans>
方式三:Spring+@EnableScheduling
首先声明一个调度对象和执行方法
import java.util.Date;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
/**
*
* @author TongYinLing
*/
@Configuration
@EnableScheduling
public class TestSchedule
{
@Scheduled(cron="0/5 * * * * *")
public void task(){
System.out.println("testSchedule:" + new Date().getTime());
}
}
关于EnableScheduling的用法可以参考:http://docs.spring.io/autorepo/docs/spring/3.2.0.M1/api/org/springframework/scheduling/annotation/EnableScheduling.html
文章中介绍说要另外声明一个AppConfig作为父级类,我觉得好像没必要,而且当有多个任务对象时,还要特意声明
还有在测试此方法时,发现方法会被调用两次,追其原因是由于applicationContext.xml文件被调用了两次