Spring注解形式的定时任务配置详解(转)

来源:互联网 发布:安卓博德之门2修改数据 编辑:程序博客网 时间:2024/05/01 06:37


一 SpringContext.xml中添加以下配置

1. beans添加xmlns:task

?
1
xmlns:task="http://www.springframework.org/schema/task"

2. xsi:schemaLocation中添加

?
1
2
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.1.xsd

3. 添加bean和task标签

  1. <!—开启这个配置,spring才能识别@Scheduled注解   -->  
  2.     <task:annotation-driven scheduler="qbScheduler" mode="proxy"/>  
  3.     <task:scheduler id="qbScheduler" pool-size="10"/>  

说明:理论上只需要加上<task:annotation-driven />这句配置就可以了,这些参数都不是必须的。


4. 添加扫描包

?
1
<context:component-scan base-package="com.task.springTask"></context:component-scan>


二 定时任务Java代码

?
1
2
3
4
5
6
7
8
9
10
11
12
packagecom.task.springTask;
 
importorg.springframework.scheduling.annotation.Scheduled;
importorg.springframework.stereotype.Component;
 
@Component("springTask")
publicclass SpringTask {
    @Scheduled(cron = "0/2 * * * * ?")
    publicvoid myTask() {
        System.out.println("这个任务两秒执行一次!");
    }
}


执行效果如图:

\


0 0