Implementing scheduled tasks using Spring's @Scheduled

Spring configuration file xmlns added

xmlns:task="http://www.springframework.org/schema/task"

added to xsi:schemaLocation

     http://www.springframework.org/schema/task
     http://www.springframework.org/schema/task/spring-task-3.0.xsd"

Spring scan annotation configuration

 

<context:component-scan base-package="com.test"/>

 

Task Scan Notes

<task:executor id="executor" pool-size="5" />  
<task:scheduler id="scheduler" pool-size="10" />  
<task:annotation-driven executor="executor" scheduler="scheduler" />

 

kind:

@Component

public class TestScheduled {

@Scheduled(cron="0/5 * *  * * ? ")

public void test(){

System.out.println("this is test shecdule");

}

}

 

 

Note: When I first started the test, the scheduled task was not executed. I checked the configuration of springmvc and found that:

<context:component-scan base-package="com.testm" use-default-filters="false">

        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>

        <context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>

    </context:component-scan>

在配置中使用了 use-default-filters 这个的默认属性是true,默认自动扫描带有@Component、@Repository、@Service和@Controller的类。而我配置成了false,所以没有执行注解类为@Component的定时任务。改为以下方式即可:

<context:component-scan base-package="com.testm" use-default-filters="false">

        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>

        <context:include-filter type="annotation" expression="org.springframework.stereotype.Component"/>

        <context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>

    </context:component-scan>

把Component注解加入扫描的范围即可。

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326497959&siteId=291194637