使用SpringTask 進行Java定時任務開發

(我這裏的案例 是模擬 將項目包放到tomcat裏面運行 )web

新建一個Java Web的Maven項目....... 此過程省略...spring

項目結構如圖:apache

一、pom.xml 配置tomcat

<?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>

二、配置spring_root.xml 文件app

<?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>

三、新建一個 定時任務類maven

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 ...ui

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

其中 cron = "0/1 * *  * * ?"  表明這着 每一秒鐘執行一次任務。spa

 

在線 cron 表達式生成器:http://cron.qqe2.com/線程

相關文章
相關標籤/搜索