scheduled注解做定时任务正解(无坑)

18 篇文章 1 订阅

如何使用schedule来做定时任务:

1.首先在springmvc.xml配置文件上加上约束文档:

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

要注意添加的时候要对应好,不然解析的时候会出现问题。

2.开启注解配置,扫描对应的类,开启定时任务,配置任务调度器

<!-- 自动扫描controller -->
 	<context:component-scan base-package="com.jobs.controller"/>  
 	<!-- 开启定时 -->
 	<task:annotation-driven/>
 	 <!-- 任务调度器 --> 	
 	 <task:scheduler id="scheduler" pool-size="10" />	
 	 <!--开启注解调度支持 @Scheduled -->  	
 	 <task:annotation-driven executor="scheduler" proxy-target-class="true"/>

这里配置容易出现的问题

 Configuration problem: Only one AsyncAnnotationBeanPostProcessor may exist within the context.

这是因为定时配置重复了,把开启定时的那一行删去就好了

3.注释设置定时任务

@Scheduled(cron = "0/2 * * * * ?")
	public void getdata() {
		System.out.println("aa");
	}

注意这个类一定要被springmvc那个扫描能扫到啊!

@Scheduled(cron = "0/2 * * * * ?")不懂的话请自行百度。

出现问题:发现定时器没有执行,需要请求才能执行:

这是因为servlet采取懒加载机制,只有在调用的时候才会去加载。

解决办法:

修改web.xml

在创建servlet的过程中加上设置load-on-startup>=1;

<servlet>
		<servlet-name>springmvc</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:config/springmvc.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>

load-on-startup=1的作用请自行百度。

ok,解决问题。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值