@Scheduled註解實現多線程,開啓定時任務

pom.xml

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

    <dependencies>
        <dependency><!--添加Web依賴 -->
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency><!--添加MySql依賴 -->
             <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency><!--添加Mybatis依賴 配置mybatis的一些初始化的東西-->
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.1</version>
        </dependency>
        <dependency><!-- 添加mybatis依賴 -->
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.5</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.1</version>
            <scope>compile</scope>
        </dependency>
    </dependencies>

Application

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
//@MapperScan( "com.mmzs.springboot.s00.application")
public class StaticScheduleTaskApplication {
    public static void main(String[] args) {
        SpringApplication.run(StaticScheduleTaskApplication.class, args);
    }
}

MultithreadScheduleTask

import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;


//@Component註解用於對那些比較中立的類進行註釋;
//相對與在持久層、業務層和控制層分別採用 @Repository、@Service 和 @Controller 對分層中的類進行註釋
@Component
@EnableScheduling   // 1.開啓定時任務
@EnableAsync        // 2.開啓多線程
public class MultithreadScheduleTask {

        @Async
        @Scheduled(fixedDelay = 1000)  //間隔1秒
        public void first() throws InterruptedException {
            System.out.println("第一個定時任務開始 : " + LocalDateTime.now().toLocalTime() + "\r\n線程 : " + Thread.currentThread().getName());
            System.out.println();
            Thread.sleep(1000 * 10);
        }

        @Async
        @Scheduled(fixedDelay = 2000)
        public void second() {
            System.out.println("第二個定時任務開始 : " + LocalDateTime.now().toLocalTime() + "\r\n線程 : " + Thread.currentThread().getName());
            System.out.println();
        }
    }

控制檯

在這裏插入圖片描述

發佈了48 篇原創文章 · 獲贊 29 · 訪問量 2563
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章