定時任務@Scheduled註解的使用

一、準備POM

<?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.yale</groupId>
    <artifactId>sb-task</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.3.RELEASE</version>
    </parent>

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

</project>

二、配置類

package com.yale.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;
    }
}

三、Task

package com.yale.task;

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

@Component
public class TestTask1 {
    private int count=0;

    @Scheduled(cron="*/6 * * * * ?")
    private void process(){
        System.out.println("[" + Thread.currentThread().getName() + "]" + "this is scheduler task runing  "+(count++));
    }
}

package com.yale.task;

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

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

@Component
public class TestTask2 {
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

    @Scheduled(fixedRate = 6000)
    public void reportCurrentTime() {
        System.out.println("[" + Thread.currentThread().getName() + "]" + "現在時間:" + dateFormat.format(new Date()));
    }
}

四、測試

mvn spring-boot:run

控制檯輸出:
[INFO] --- spring-boot-maven-plugin:1.5.3.RELEASE:run (default-cli) @ sb-task ---

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.5.3.RELEASE)

2019-03-18 20:40:14.912  INFO 6272 --- [           main] com.yale.Application                     : Starting Application on USER-20160707JH with PID 6272 (D:\idea_workspace\springboot_test\sb-task\target\classes started by Administrator in D:\idea_workspace\springboot_test\sb-task)
2019-03-18 20:40:14.917  INFO 6272 --- [           main] com.yale.Application                     : No active profile set, falling back to default profiles: default
2019-03-18 20:40:15.100  INFO 6272 --- [           main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@782dc4: startup date [Mon Mar 18 20:40:15 CST 2019]; root of context hierarchy
2019-03-18 20:40:15.904  INFO 6272 --- [           main] o.s.s.c.ThreadPoolTaskScheduler          : Initializing ExecutorService  'taskScheduler'
2019-03-18 20:40:16.106  INFO 6272 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
[spring-task-thread1]現在時間:20:40:16
2019-03-18 20:40:16.140  INFO 6272 --- [           main] com.yale.Application                     : Started Application in 1.679 seconds (JVM running for 8.238)
[spring-task-thread2]this is scheduler task runing  0
[spring-task-thread1]現在時間:20:40:22
[spring-task-thread3]this is scheduler task runing  1
[spring-task-thread2]現在時間:20:40:28
[spring-task-thread4]this is scheduler task runing  2
[spring-task-thread1]現在時間:20:40:34
[spring-task-thread5]this is scheduler task runing  3
[spring-task-thread3]現在時間:20:40:40
[spring-task-thread6]this is scheduler task runing  4
[spring-task-thread2]現在時間:20:40:46
[spring-task-thread7]this is scheduler task runing  5
[spring-task-thread4]現在時間:20:40:52
[spring-task-thread8]this is scheduler task runing  6
Disconnected from the target VM, address: '127.0.0.1:2481', transport: 'socket'

Process finished with exit code -1

五、參數說明

@Scheduled所支持的參數:

  1. cron:cron表達式,指定任務在特定時間執行;
  2. fixedDelay:表示上一次任務執行完成後多久再次執行,參數類型爲long,單位ms;
  3. fixedDelayString:與fixedDelay含義一樣,只是參數類型變爲String;
  4. fixedRate:表示按一定的頻率執行任務,參數類型爲long,單位ms;
  5. fixedRateString: 與fixedRate的含義一樣,只是將參數類型變爲String;
  6. initialDelay:表示延遲多久再第一次執行任務,參數類型爲long,單位ms;
  7. initialDelayString:與initialDelay的含義一樣,只是將參數類型變爲String;
  8. zone:時區,默認爲當前時區,一般沒有用到。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章