SpringBoot项目实现定时任务一种特别简单的办法

SpringBoot项目想要实现定时任务一种特别简单的办法

1、创建SpringBoot 项目,导入依赖

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

2、在启动类加上注解:@EnableScheduling

@SpringBootApplication
@EnableScheduling
public class SchedulingApplication {
    public static void main(String[] args) {
        SpringApplication.run(SchedulingApplication.class,args);
    }
}

3、编写一个类,编写你想要定时执行的方法

@Component
public class SchedulTest {
    @Scheduled(cron = "0/5 * * * * ?")
    public void testSchedul() {
        System.out.println("================ 测试 =======================");
    }

    @Scheduled(cron = "0/1 * * * * ?")
    public void testSchedul2() {
        System.out.println("********************** 测试2 **********************");
    }
}

启动项目测试:‘’
在这里插入图片描述
这里说一点: @Scheduled里面写的表达式为Cron表达式

题外话:我们可以在SchedulTest类里面注入一些Service,就可以调用Service的方法,来满足我们实际的需求了。

要想SpringBoot 项目已启动就执行某个方法

1、写一个类实现 CommandLineRunner 接口即可

@Component
public class RannerTest implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.out.println("项目启动了");
    }
}
 

2、测试结果:
在这里插入图片描述

题外话:我们也可以在RannerTest类里面注意一些service,实现我们的业务逻辑

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值