Spring定时任务之注解方式实现

Spring框架提供了对任务调度与执行的支持,本文介绍了利用Spring注解方式实现定时任务。

所需的jar包:

1、spring-beans-5.0.2.RELEASE.jar

2、spring-context-5.0.2.RELEASE.jar

3、spring-core-5.0.2.RELEASE.jar

4、spring-web-5.0.2.RELEASE.jar

5、spring-aop-5.0.2.RELEASE.jar

6、spring-expression-5.0.2.RELEASE.jar

7、spring-jcl-5.0.2.RELEASE.jar


第一步:配置web.xml

 ContextLoaderListener是Spring提供的一个监听器实现类,通过该监听器,web项目在启动时会启动Spring容器。

代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>spring</display-name>
    <listener>  
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
    </listener>  

</web-app>

第二步:添加applicationContext.xml配置文件

 在第一步的配置方式下,web项目启动时,Spring会自动到WEB_INF下寻找applicationContext.xml文件,

读取配置,初始化bean。applicationContext.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-4.3.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/task 
        http://www.springframework.org/schema/task/spring-task.xsd">


        <!-- 启用注解方式 -->
        <task:annotation-driven  />
        
        <!-- 扫描定时任务类所在的包 -->
        <context:component-scan base-package="com.task"></context:component-scan>

</beans>  

第三步:编写代码

新建com.task包,在该包下编写SpringTask类,具体代码如下:

import java.util.Date;


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


/**
 * @author Pei
 * @date 2018年2月9日
 */
@Component
public class SpringTask {


// fixedRate表示为定时循环任务,毫秒级
@Scheduled(fixedRate = 1000)
public void showDate() {
System.out.println("showDate()方法执行:" + new Date());
}


// fixedRate表示为定时循环任务,毫秒级
@Scheduled(cron = "0/5 * * * * ? ")
public void showTime() {
System.out.println("showTime()方法执行:" + new Date());
}

}

该类里面实现了两种任务执行的方式,fixedRate 是在Spring启动时就会执行,按指定的时间间隔执行,

第二种是利用cron表达式进行执行。

执行结果如下:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值