Springboot 整合Schedule 定时任务

在项目开发过程中,我们经常需要执行具有周期性的任务。通过定时任务可以很好的帮助我们实现。
1. 添加依赖

   <!--定时任务-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
        </dependency>
        <!--定时任务-->

2. 在启动类中添加注解@EnableScheduling,就可以启用定时任务了
如:

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

3. 编写定时任务调度方法

package com.hadwinling.scheduletask;

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

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Component
public class Task {

    @Scheduled(cron="0/2 * * * * ?")//每2秒执行一次
    public void schedule(){
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime time = LocalDateTime.now();
        String currentTime = df.format(time);
        System.out.println(currentTime+"===定时任务执行!!!");
    }

}

注意:在需要定时任务的方法上加上@Scheduled注解表示该方法将进行调度

其中的属性cron为定时任务的调度时间间隔,本次示例为每2秒调度一次。

cron表达式的写法将在附录给出。
Spring Schedule三种任务调度器分别举例说明。

 @Scheduled(cron="0/2 * * * * ?")

Cron表达式由6或7个空格分隔的时间字段组成:
在这里插入图片描述
常用的cron 表达式:
在这里插入图片描述
给大家一个生成cron表达式网址:http://cron.qqe2.com/

固定间隔任务使用这个注解@Scheduled(fixedDelay = 1000*10)
@Scheduled(fixedDelay = 1000*10): 这个是每次任务结束后10秒执行

固定频率任务@Scheduled(fixedRate = 1000*10)
@Scheduled(fixedRate = 1000*10):表示任务这个是每10秒执行一次

4. 启动SpringBoot,观察控制台输出

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值