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

Spring任务调度和异步方法实例

2014-12-06 13:49 686 查看
最近系统的学习了Spring实战,发现了Spring不少的使用功能,今天记录下Spring任务调度和异步方法的实例。

Spring配置文件:

<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:aop="http://www.springframework.org/schema/aop" 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-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">
<bean id="task" class="com.jzli.springInAction.ch05.ScheduledTask" />

<task:annotation-driven />
</beans>

任务类:
package com.jzli.springInAction.ch05;

import java.util.Date;
import java.util.concurrent.TimeUnit;

import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;

public class ScheduledTask {

@Scheduled(fixedRate = 1000)
public void task1() {
System.out.println(new Date().toLocaleString() + ":" + "Task1");
}

@Scheduled(cron = "0 0/1 * * * *")
public void task2() {
System.out.println(new Date().toLocaleString() + ":" + "Task2");
}

/**
* 异步方法
*
* @throws Exception
*/
@Async
public void heavyTask() throws Exception {
TimeUnit.SECONDS.sleep(10);
System.out.println("完成耗时任务!");
}

}

测试类:
package com.jzli.springInAction.ch05.test;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.jzli.springInAction.ch05.ScheduledTask;
/**
* 任务调度和异步方法的实例
*/
public class TaskTest {

public static void main(String[] args) throws Exception {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
"ch05/tasks.xml");
ScheduledTask task = (ScheduledTask) context.getBean("task");
task.heavyTask();
System.out.println("完成任务");

}

}

在此做个记录和分享!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: