原创

【Spring MVC】定时任务 spring xml 定时任务配置 设置 listener 项目启动时启动

欢迎转载:攻城狮不是猫

1、编写 listener 监听类

import com.xxx.xxxx.scheduledtasks.ScheduledTasks;
import org.springframework.web.context.support.WebApplicationContextUtils;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class TaskListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
//获得定时任务bean 项目启动时启动
ScheduledTasks scheduledTasks = WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext()).getBean(ScheduledTasks.class);
scheduledTasks.taskWebServiceCheck();
}

@Override
public void contextDestroyed(ServletContextEvent sce) {

}
}

3、编写定时任务类(@Component不要丢了

@Component
public class ScheduledTasks {
private static final Logger logger = LoggerFactory.getLogger(ScheduledTasks.class);
    //@Scheduled(fixedRate = 1000 * 60 * 10)
public void taskWebServiceCheck(){
//定时任务执行内容
}    }

@Scheduled(fixedRate = 60000)//基于注解方式 这是每隔一分钟执行一次
public void getServerInfoLog(){
//定时任务执行内容

}



3、编写监听

        注意这个监听要在spring的监听后面否则上面的监听类会加载不到类 org.springframework.web.context.ContextLoaderListener

<!-- 定时任务启动执行 -->
<listener>
<listener-class>com.wengine.bgmanage.listener.TaskListener</listener-class>
</listener>

5、配置定时任务xml (红色字部分需要)

<?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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:p="http://www.springframework.org/schema/p"
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-4.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-4.1.xsd

http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-4.0.xsd">

<!-- 启用注解 -->
<context:annotation-config />

<!--配置任务扫描-->
<task:annotation-driven />
<!-- 扫描任务 -->
<context:component-scan base-package="com.xxxx.xxxx.scheduledtasks" />
<!-- 注册定时类 -->
<bean id="scheduledTasks" class="com.xxxx.xxxx.scheduledtasks.ScheduledTasks"></bean>
<!-- 定时时间配置 -->
<task:scheduled-tasks>
<task:scheduled ref="scheduledTasks" method="taskWebServiceCheck" cron="0 0/5 * * * ?" />
</task:scheduled-tasks>
</beans>
正文到此结束
Loading...