最近系統的學習了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("完成任務");
}
}
在此做個記錄和分享!