@Scheduled注解实现多线程,开启定时任务

桃扇骨 2023-06-28 06:21 80阅读 0赞

pom.xml

  1. <parent>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter</artifactId>
  4. <version>2.0.4.RELEASE</version>
  5. </parent>
  6. <dependencies>
  7. <dependency><!--添加Web依赖 -->
  8. <groupId>org.springframework.boot</groupId>
  9. <artifactId>spring-boot-starter-web</artifactId>
  10. </dependency>
  11. <dependency><!--添加MySql依赖 -->
  12. <groupId>mysql</groupId>
  13. <artifactId>mysql-connector-java</artifactId>
  14. </dependency>
  15. <dependency><!--添加Mybatis依赖 配置mybatis的一些初始化的东西-->
  16. <groupId>org.mybatis.spring.boot</groupId>
  17. <artifactId>mybatis-spring-boot-starter</artifactId>
  18. <version>1.3.1</version>
  19. </dependency>
  20. <dependency><!-- 添加mybatis依赖 -->
  21. <groupId>org.mybatis</groupId>
  22. <artifactId>mybatis</artifactId>
  23. <version>3.4.5</version>
  24. <scope>compile</scope>
  25. </dependency>
  26. <dependency>
  27. <groupId>org.mybatis</groupId>
  28. <artifactId>mybatis-spring</artifactId>
  29. <version>1.3.1</version>
  30. <scope>compile</scope>
  31. </dependency>
  32. </dependencies>

Application

  1. import org.springframework.boot.SpringApplication;
  2. import org.springframework.boot.autoconfigure.SpringBootApplication;
  3. @SpringBootApplication
  4. //@MapperScan( "com.mmzs.springboot.s00.application")
  5. public class StaticScheduleTaskApplication {
  6. public static void main(String[] args) {
  7. SpringApplication.run(StaticScheduleTaskApplication.class, args);
  8. }
  9. }

MultithreadScheduleTask

  1. import org.springframework.scheduling.annotation.Async;
  2. import org.springframework.scheduling.annotation.EnableAsync;
  3. import org.springframework.scheduling.annotation.EnableScheduling;
  4. import org.springframework.scheduling.annotation.Scheduled;
  5. import org.springframework.stereotype.Component;
  6. import java.time.LocalDateTime;
  7. //@Component注解用于对那些比较中立的类进行注释;
  8. //相对与在持久层、业务层和控制层分别采用 @Repository、@Service 和 @Controller 对分层中的类进行注释
  9. @Component
  10. @EnableScheduling // 1.开启定时任务
  11. @EnableAsync // 2.开启多线程
  12. public class MultithreadScheduleTask {
  13. @Async
  14. @Scheduled(fixedDelay = 1000) //间隔1秒
  15. public void first() throws InterruptedException {
  16. System.out.println("第一个定时任务开始 : " + LocalDateTime.now().toLocalTime() + "\r\n线程 : " + Thread.currentThread().getName());
  17. System.out.println();
  18. Thread.sleep(1000 * 10);
  19. }
  20. @Async
  21. @Scheduled(fixedDelay = 2000)
  22. public void second() {
  23. System.out.println("第二个定时任务开始 : " + LocalDateTime.now().toLocalTime() + "\r\n线程 : " + Thread.currentThread().getName());
  24. System.out.println();
  25. }
  26. }

控制台

在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,80人围观)

还没有评论,来说两句吧...

相关阅读