【SpringBoot】启动定时任务

本文适用于SpringBootv2.5.4版本。

例程下载: https://files.cnblogs.com/files/heyang78/myBank-timedtask-210911_2129.rar

使用前提:

1.pom.xml引入spring-boot-starter-web依赖

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

因为Spring task包含在spring-context.jar中。

2.启动类加入@EnableScheduling注解

@EnableScheduling
@SpringBootApplication
public class MyBankApplication {

    public static void main(String[] args) {
        SpringApplication.run(MyBankApplication.class, args);
    }

}

完成以上两步后,就可以书写定时任务类了。

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

@Component
public class TestTask {
    @Scheduled(cron="*/5 * * * * ?")
    public void run() {
        System.out.println("Hello");
    }
}

这里要注意两点,第一是类名一定要加@Component,不加任务就启动不起来;第二要定时运行的函数要加@Scheduled,之后写克龙表达式。关于克龙表达式的写法可以参考:

 https://www.cnblogs.com/heyang78/p/3678650.html

之后,run函数就每隔五秒运行一次了。

-END--

原文地址:https://www.cnblogs.com/heyang78/p/15256838.html