1. 程式人生 > >spring3中springTask定時任務

spring3中springTask定時任務

spring-task是Spring3.0以後自主開發的定時任務工具,我們可以將它比作一個輕量級的Quartz,而且使用起來很簡單,除spring相關的包外不需要額外的包,而且支援註解和配置檔案兩種配置方式。

一、使用註解配置(spring)

1、pom.xml中引入spring的一些基礎包

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

2、spring.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:aop="http://www.springframework.org/schema/aop"
 xmlns:tx="http://www.springframework.org/schema/tx"
 xmlns:cache="http://www.springframework.org/schema/cache"
 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-4.3.xsd
          http://www.springframework.org/schema/aop
          http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
          http://www.springframework.org/schema/tx
          http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
          http://www.springframework.org/schema/cache
          http://www.springframework.org/schema/cache/spring-cache-4.3.xsd
          http://www.springframework.org/schema/task
   http://www.springframework.org/schema/task/spring-task-4.3.xsd">
          
      <!-- 專案包掃描-->
    <context:component-scan base-package="com.tingcream.springTask1">
    </context:component-scan> 
     

   <!-- task 註解驅動支援 重要-->
    <task:annotation-driven/>
      <!-- 指定sheduler 執行緒池大小,否則預設為單執行緒 -->
     <task:scheduler id="scheduler" pool-size="10"/> 

</beans>

注意spring.xml中引入xmlns:task 的名稱空間和schema地址,即

 xmlns:task="http://www.springframework.org/schema/task"
http://www.springframework.org/schema/task

http://www.springframework.org/schema/task/spring-task-4.3.xsd

 

3、任務bean

package com.tingcream.springTask1;

import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class MyTask {
 
 //@Scheduled(fixedDelay=1000)// fixedDelay:表示從上一次任務執行結束到下一次任務開始的時間間隔  毫秒
 //@Scheduled(fixedRate=3000)//fixedRate:表示從上一次任務開始到下一次任務開始的時間間隔  毫秒
 @Scheduled(cron = "*/3 * * * * ?")// cron:表示使用cron表示式來表示排程週期(日曆)  功能最為強大
 public void work1 () {
  Thread t = Thread.currentThread();
 
 System.out.println(t.getName()+"::work1執行:"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) );
 }
 @Scheduled(cron = "*/3 * * * * ?")
 public void work2 () {
 Thread t = Thread.currentThread();
 
 System.out.println(t.getName()+"::work2執行:"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) );
 }

}

二、使用xml配置檔案(spring)

1、pom.xml中引入spring的一些基礎包

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

2、spring.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:aop="http://www.springframework.org/schema/aop"
 xmlns:tx="http://www.springframework.org/schema/tx"
 xmlns:cache="http://www.springframework.org/schema/cache"
 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-4.3.xsd
          http://www.springframework.org/schema/aop
          http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
          http://www.springframework.org/schema/tx
          http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
          http://www.springframework.org/schema/cache
          http://www.springframework.org/schema/cache/spring-cache-4.3.xsd
          http://www.springframework.org/schema/task
   http://www.springframework.org/schema/task/spring-task-4.3.xsd">
           <!-- 專案包掃描-->
    <context:component-scan base-package="com.tingcream.springTask2">
    </context:component-scan> 

     <task:scheduler id="scheduler" pool-size="10"/> 
    
     <task:scheduled-tasks> 
             <task:scheduled ref="myJob" method="work1" cron="*/1 * * * * ?"/> 
             <task:scheduled ref="myJob" method="work2" cron="*/1 * * * * ?"/> 
      </task:scheduled-tasks> 
    
</beans>

3、任務bean

package com.tingcream.springTask2;

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

import org.springframework.stereotype.Component;

@Component
public class MyJob {
 
 public void work1 () {
  Thread t = Thread.currentThread();
  
 System.out.println(t.getName()+"::work1執行:"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) );
 }
 public void work2 () {
 Thread t = Thread.currentThread();
 
 System.out.println(t.getName()+"::work2執行:"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) );
 }
  
}

 

三、springboot專案中使用springTask

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.ruihao</groupId>
	<artifactId>springTask3</artifactId>
	<version>1.0</version>
	<packaging>jar</packaging>

	<name>springTask3</name>
	<description>Demo project for Spring Boot</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.17.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>


</project>

2、springboot啟動類,新增@EnableScheduling註解開啟task支援

package com.tingcream.springTask3;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling
public class SpringTask3Application {

 public static void main(String[] args) {
 SpringApplication.run(SpringTask3Application.class, args);
 }
}

3、任務bean

@Component
public class MyJob {
 private int count=0;
    @Scheduled(cron="*/2 * * * * ?")
    private void run(){
      count++;
        System.out.println("[" + Thread.currentThread().getName() + "]" + "MyJob 執行  "+(count));
    }

}
@Component
public class MyJob2 {
 private int count=0;

    @Scheduled(cron="*/2 * * * * ?")
    private void run(){
     count++;
        System.out.println("[" + Thread.currentThread().getName() + "]" + "MyJob2 執行  "+(count));
    }
}

3、配置task的多執行緒支援 

package com.tingcream.springTask3.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

@Configuration
@EnableScheduling
public class SchedulerConfig {
    @Bean
    public TaskScheduler taskScheduler() {
        ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
        //執行緒池大小
        scheduler.setPoolSize(10);
        //執行緒名字字首
        scheduler.setThreadNamePrefix("spring-task-thread");
        return scheduler;
    }
}