Spring注解定时器的实现

时间:2022-10-27 23:29:18
第一步:配好依赖
<dependency>  
        <groupId>org.springframework</groupId>  
        <artifactId>spring-context</artifactId>  
        <version>4.1.7.RELEASE</version>  
    </dependency>  
    <dependency>  
        <groupId>org.springframework</groupId>  
        <artifactId>spring-web</artifactId>  
        <version>4.1.6.RELEASE</version>  
    </dependency>  
    <dependency>  
        <groupId>org.springframework</groupId>  
        <artifactId>spring-webmvc</artifactId>  
        <version>4.1.6.RELEASE</version>  
    </dependency> 


第二步:添加task相关的配置
<?xml version="1.0" encoding="UTF-8"?>  
<beans 
xmlns:task="http://www.springframework.org/schema/task"  
xmlns="http://www.springframework.org/schema/beans" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
xmlns:context="http://www.springframework.org/schema/context"  
xsi:schemaLocation="  
http://www.springframework.org/schema/beans  
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
http://www.springframework.org/schema/context  
http://www.springframework.org/schema/context/spring-context-3.0.xsd  
http://www.springframework.org/schema/task  
http://www.springframework.org/schema/task/spring-task-3.1.xsd">  
  
    <!-- 开启定时任务 -->  
    <task:annotation-driven />  
    <!-- 开启注解 -->  
    <context:annotation-config />  
    <!-- 指定相关的包路径 -->  
    <context:component-scan base-package="org.fkit.task"/>  
</beans>

第三步:编写pojo
package org.fkit.task;


import java.text.SimpleDateFormat;
import java.util.Date;


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


@Component("taskJob")
public class TaskJob {
@Scheduled(cron = "0/5 * * * * ?")
public void schTest1() {
Date date = new Date();
SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateStr = sim.format(date);
System.out.println("这是spring定时器1,每五秒执行一次,当前时间:" + dateStr);
}
}


第四步:启动tomcat