Quartz是重量級的計划任務實現方式,對於一些簡單的計划任務,Spring3中提供了task,用於實現計划任務,一般情況下足夠用了。
下面介紹如何在spring3中使用task:
1.spring配置文件上添加對task的描述
<beans xmlns="http://www.springframework.org/schema/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.0.xsd">
2.spring配置文件中設置具體的任務
cron表達式的介紹可以參考其他文檔,跟Quartz的表達式是一樣的,"0 * * * * ?"是指每分鍾執行該任務,任務內容為taskJob中work方法
<task:scheduled-tasks> <task:scheduled ref="taskJob" method="work" cron="0 * * * * ?"/> </task:scheduled-tasks>
3.對應的TaskJob類文件如下:
package com.company.web.servlet; import org.springframework.stereotype.Service; @Service public class TaskJob { public void work() { System.out.println(123); } }
由於這里使用了注解,需要在spring配置文件中設置掃描路徑,如果未使用注解,把QuzrtzJob類加入spring配置文件即可
<context:component-scan base-package="com.company.web.servlet" />
task也可以使用注解的方式實現,本文不再介紹