SpringBoot单体项目-定时任务

268 阅读1分钟

今天笔记一下SpringBoot项目中简单实现定时任务过程

简简单单一个pom.xml内容:

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

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


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

编写定时任务内容:

@Component
@Slf4j
public class DemoTask {

    /**
     * 每3秒触发一次
     */
    @Scheduled(fixedDelay = 3000)
    public void taskOne() {
        log.info("三秒一次的任务执行...");
    }

    /**
     * 每5秒触发一次
     */
    @Scheduled(cron = "0/5 * * * * ? ")
    public void taskTwo() {
        log.info("每五秒一次的任务执行...");
        try {
            Thread.sleep(4000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}

启动类启动定时任务注解:@EnableScheduling

@SpringBootApplication
@Slf4j
@EnableScheduling
public class ScheduledDemoApplication {

    public static void main(String[] args) {

        SpringApplication.run(ScheduledDemoApplication.class, args);
        log.info("ScheduledDemoApplication started");
    }
}

直接启动项目:

image.png

默认:定时任务执行只有一条线程,互相影响,改造为多线程,实现每个定时任务互不影响

@SpringBootConfiguration
public class SchedulingConfig implements SchedulingConfigurer {
    /**
     * @param taskRegistrar
     */
    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {

        // 设置定时任务线程池数量
        taskRegistrar.setScheduler(Executors.newScheduledThreadPool(5));
    }
}

观察:

image.png

每个定时任务独立线程执行,互不影响。