spring 使用注解来调度定时任务

本文介绍如何在Spring框架中配置并实现定时任务。主要内容包括:在配置文件中添加必要的命名空间和schemaLocation;配置自动调度所需的包扫描、任务执行器及调度器;通过注解的方式实现定时任务;以及在web.xml中指定启动时要加载的配置文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.在需要加载spring的配置文件里spring.xml / applicationContext.xml 添加

xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="
http://www.springframework.org/schema/task        
http://www.springframework.org/schema/task/spring-task-3.0.xsd

2.配置自动调度的包和定时开关

<!-- 自动调度需要扫描的包 -->
	<context:component-scan base-package="*" /> 
	<task:executor id="executor" pool-size="5" />    
    <task:scheduler id="scheduler" pool-size="10" />  
    <task:annotation-driven executor="executor" scheduler="scheduler" />

3.配置调度和注解调度

<!-- 配置调度 需要在类名前添加 @Service -->
    <!--  
	    <task:scheduled-tasks>
	    	<task:scheduled ref="demoTask" method="myTestWork" cron="0/10 * * * * ?"/>
	    </task:scheduled-tasks>
    -->
    <!-- 不通过配置调度,需要在类名前 @Component/@Service,在方法名 前添加@Scheduled(cron="0/5 * * * * ? ")-->

4.在web.xml配置里添加启动时要扫描的配置文件和监听

 <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext*.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

5.添加调度的包

6.类测试

@Service
public class demo {
	@Scheduled(cron="0/5 * * * * ? ")
	public void myTestWork(){
		
		System.out.println("ssss");
	}

}







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值