SpringBoot使用SpringTask实现定时任务

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014248473/article/details/88649795

一、准备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:时区,默认为当前时区,一般没有用到。

猜你喜欢

转载自blog.csdn.net/u014248473/article/details/88649795