您的位置:首页 > 编程语言 > Java开发

spring3中使用注解方式实现定时器调度任务

2013-11-05 15:28 796 查看
2013-11-05 15:25:42

1首先在applicationContext.xml中引入

<!--
spring3.0注解定时器任务
xmlns:task="http://www.springframework.org/schema/task"
 http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">
-->


2打开定时器开关

不使用注解时,<task:scheduled ref="taskTest" method="hello" cron="10/5 * * * * ?"/>

<task:scheduled ref = "实体类的beanid" method="方法名" cron="表达式">

<!-- 定时器开关 -->
  
  

<task:annotation-driven/>

<!-- cron="10/5 * * * * ?" 每分钟延迟10秒开始执行,5秒执行一次
<bean id = "taskTest" class="com.test.task.TaskTest"></bean>
<task:scheduled-tasks>
<task:scheduled ref="taskTest" method="say"   cron="10/5 * * * * ?"/>
<task:scheduled ref="taskTest" method="hello" cron="10/5 * * * * ?"/>
</task:scheduled-tasks>
-->


3编写任务实例
使用注解时在类头部添加@Component 方法头部添加@Scheduled

package com.test.task;

import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class TaskTest {
public void say(){
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("时间为:"+ sdf.format(date));
}

public void hello(){
System.out.println("HelloWorld");
}

@Scheduled(fixedDelay = 5000)
void doSomethingWithDelay(){
System.out.println("I'm doing with delay now!");
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("基于注解的定时器启动,时间为:"+ sdf.format(date));
}

@Scheduled(fixedRate = 5000)
void doSomethingWithRate(){
System.out.println("I'm doing with rate now!");
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("基于注解的定时器启动,时间为:"+ sdf.format(date));
}

@Scheduled(cron = "0/5 * * * * *")
void doSomethingWith(){
System.out.println("I'm doing with cron now!");
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("基于注解的定时器启动,时间为:"+ sdf.format(date));
}

}


常用cron 表达式:http://wenku.baidu.com/link?url=mbfyoa3VGn57euEd1jC-VKkrpimxZx7RSLs4VkF_ZCIDna2AnioEIbKnDJDtqfyHtG6X0-LGVcWFmgNQ_slujsISy5iHCRsHEj4UAnHnuXq
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: