ssm定时任务的实现

来源:互联网 发布:工程造价软件破解版 编辑:程序博客网 时间:2024/06/09 06:18

一、单独建立一个目录结构用来存放定时任务

二、创建task的配置文件  我起的名字是spring-task.xml,并将配置文件在web.xml中进行配置。如下所示



三,补充spring-task.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: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.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsdhttp://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd"       default-autowire="byName" default-lazy-init="false">    <!--配置包扫描-->    <context:component-scan base-package="util.timer" />    <!-- 定时任务配置 scheduler 方式 注解 -->    <task:executor id="executor" pool-size="5"/>    <task:scheduler id="scheduler" pool-size="10"/>    <task:annotation-driven executor="executor" scheduler="scheduler"/></beans>

记得编写的Java定时任务类要放在包扫描的路径下

四、编写定时任务类


package util.timer;import org.springframework.scheduling.annotation.Scheduled;import org.springframework.stereotype.Component;/*** Created by Administrator on 2017/12/20. */@Componentpublic class TimerTask {    @Scheduled(cron = "0/2 * * * * ?")//每隔2秒隔行一次    public void test2()    {        System.out.println("job2 开始执行");    }}


大家记得加上@Component注解(把普通pojo实例化到spring容器中,相当于配置文件中的<bean id="" class=""/>),否则的话,定时任务无法启动


接下来启动服务器就可以了


原创粉丝点击