【Spring MVC】定时任务 spring xml 定时任务配置 设置 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) {

    }
}
@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(){
    //定时任务执行内容

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



   com.wengine.bgmanage.listener.TaskListener

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">

   
   

   
   
   
   
   
   
   
   
      
   

你可能感兴趣的:(Spring4,实战读书笔记)