使用SpringTask 进行Java定时任务开发

(我这里的案例 是模拟 将项目包放到tomcat里面运行 )

新建一个Java Web的Maven项目....... 此过程省略...

项目结构如图:

1、pom.xml 配置

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.zh</groupId>
  <artifactId>oukele</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>oukele Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
  </properties>

  <dependencies>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>4.1.6.RELEASE</version>
    </dependency>

    <!-- spring web jar包 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>4.1.6.RELEASE</version>
    </dependency>


  </dependencies>

</project>

2、配置spring_root.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:contxt="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.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">

    <!-- 扫描某某包下面使用@Component注解的类 将其实例化,放入spring容器中   -->
    <contxt:component-scan base-package="com.zh.oukele.spring_task"/>
    <!-- 启用定时任务的注解驱动   -->
    <task:annotation-driven/>
    <!--  注:spring定时任务默认单线程,推荐配置线程池,若不配置多任务下会有问题。  -->
    <task:scheduler id="poolTaskScheduler" pool-size="10"/>

</beans>

3、新建一个 定时任务类

package com.zh.oukele.spring_task;

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

/**
 * 使用 SpringTask 制作定时任务
 */
@Component
public class SpringTask {

    @Scheduled(cron = "0/1 * *  * * ? ")
    public void downloadData(){

        System.out.println("定时任务.....");

    }

}

启动 tomcat ...

 @Scheduled(cron = "0/1 * *  * * ?")

其中 cron = "0/1 * *  * * ?"  代表这着 每一秒钟执行一次任务。

 

在线 cron 表达式生成器:http://cron.qqe2.com/

 

posted @ 2019-10-22 00:25  追梦滴小蜗牛  阅读(5647)  评论(0编辑  收藏  举报