Spring Task使用方法

Spring Task是Spring框架自带的任务调度器。提供annotation注解和XML配置两种配置方式。

本文简记XML的配置方式。

1:新建task-config.xml配置文件

1
2
3
4
5
6
7
8
9
10
11
12
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:task="http://www.springframework.org/schema/task"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
</beans>

2:新建任务调度接口JobService,并添加测试方法test

1
2
3
4
5
package org.server.task;
public interface JobService {
void test();
}

3:新建任务调度接口实现类JobServiceImpl,并实现测试方法test

1
2
3
4
5
6
7
8
9
10
11
12
13
package org.server.task.impl;
import org.server.task.JobService;
import org.springframework.stereotype.Service;
@Service("jobService")
public class JobServiceImpl implements JobService{
@Override
public void test() {
// 任务业务逻辑
System.out.println("---JobTask test---");
}
}

4:在配置文件中增加配置

1
2
3
4
5
6
7
8
9
10
11
<context:component-scan base-package="org.server.task" />
<bean id="taskScheduler" class="org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler">
<property name="poolSize" value="30" />
<property name="errorHandler">
<bean class="org.server.util.ScheduledTaskErrorHandler"/>
</property>
</bean>
<task:scheduled-tasks scheduler="taskScheduler">
<!-- 每秒执行一次test方法 -->
<task:scheduled ref="jobService" method="test" cron="* * * * * ?" />
</task:scheduled-tasks>

5:ErrorHandler

1
2
3
4
5
6
7
8
9
package org.server.util;
import org.springframework.util.ErrorHandler;
public class ScheduledTaskErrorHandler implements ErrorHandler {
public void handleError(Throwable t) {
// do something, like shutdown the scheduler
}
}

注意:如果任务调度器不能正常运行,请确认配置是否开启load-on-startup

1
2
3
4
5
6
7
8
9
10
<servlet>
<servlet-name>spring-mvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/*.xml</param-value>
</init-param>
<!-- 记得设定启动时加载 -->
<load-on-startup>1</load-on-startup>
</servlet>