spring定时任务:@Scheduled

版权声明:本文为博主原创文章,转载请注明出处 https://blog.csdn.net/imHanweihu/article/details/80911240

1. 在applicationContext.xml里加入task的命名空间

xmlns:task="http://www.springframework.org/schema/task"
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-4.1.xsd

2. 在applicationContext.xml中配置定时任务线程池,启用注解式定时任务

<task:annotation-driven scheduler="myScheduler"/> <!-- 定时器开关-->
<task:scheduler id="myScheduler" pool-size="5"/>

3. 方法上使用注解,指定cron

package test;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class ScheduledTest {

    @Scheduled(cron = "0/2 * * * * ? ") // 每隔2秒执行一次
    public void testScheduled(){
        System.out.println("1");
    }

}

spring的定时任务默认是单线程,多个任务执行起来时间会有问题(B任务会因为A任务n秒执行一次,而延后n秒),配置了线程池就不会延后了。

@Component注解:泛指各种组件,当此类不属于mvc的归类的时候(不属于@Controller、@Services等的时候),我们就可以使用@Component来标注这个类,实例化到spring容器。

cron表达式:参考https://www.cnblogs.com/xiandedanteng/p/3678650.html

猜你喜欢

转载自blog.csdn.net/imHanweihu/article/details/80911240