在配置文件 applicationContext.xml
中添加
<beans ...
xmlns:task="http://www.springframework.org/schema/task"
...
xsi:schemaLocation="
...
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.2.xsd">
<context:annotation-config></context:annotation-config>
<!-- 使用annotation 自动注册bean,并检查@Required,@Autowired的属性已被注入 -->
<context:component-scan base-package="com.test" annotation-config="true" />
<task:annotation-driven/>
</beans>
类
package com.test.scheduled;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component("ScheduledManager")
@Lazy(value=false)
public class ScheduledManager {
/**
* 定时任务
*/
@Scheduled(initialDelay = 1000*60*10, fixedRate = 1000*60*10)
public void task(){
System.out.print("定时任务");
}
}
Spring 4.x 中需在类名前加@EnableScheduling
@Scheduled中可使用cron表达式和fixedDelay