SpringBoot定时任务配置详解

生活中经常要用定时任务,比如:

(1)比如生活中的闹钟,我们设置闹钟每天早上七点执行响铃操作。我们给这个闹钟设定了时间,并且也给它设置了要进行执行的具体任务。
(2)假如在一个电商项目中,当用户在选择商品加入订单车后,如果在两个小时内没有支付,那么就自动会被取消掉。关于这样的功能我们如何去解决呢?

在项目中可能会出现一些定时更新任务,此时就需要用到定时任务的功能,定时任务就是制定什么时间执行一次,在SpringBoot中很简单就可以实现定时任务,因为SpringBoot已经封装好了如果不是SpringBoot的话可以参考我的另外一篇文章:Java定时器、任务调度工具详解(Quartz 任务调度)

1、Springboot定时任务配置

因为很简单所以我直接上源代码,SpringBoot项目启动之后就会自动的启动我定时任务
在这里插入图片描述

package com.timer.timer.timer;

import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component                //注解表明一个类会作为组件类,并且Spring要为这个类创建bean
@Configurable             //自动注bean,不需要手动new出来
@EnableScheduling         //开启计划任务
public class Timer {


    //声明计划任务 
    @Scheduled(cron = " 0/10 * * * * ? ")
    public void doTimingPlan() {
        System.out.println("每10秒执行");
    }
}

2,注解说明

@Component : //注解表明一个类会作为组件类,并且Spring要为这个类创建bean
@Configurable ://自动注bean,不需要手动new出来
@EnableScheduling ://开启计划任务
@Scheduled ://声明计划任务(重点,什么规则都是这个注解来定义的)

重点 cron表达式

@Scheduled:注解使用方式

表达式 表达式作用
0/10 * * * * ? 每10秒执行一次
0/30 * * * * ? 每30秒执行一次
0 0 0/2 * * ? 每隔2个小时触发
0 0 0/4 * * ? 每隔4个小时触发
0 0 12 * * ? 每天中午12点触发
0 0 3 * * ? 每天下午3点执行
0 0 1 1 * ? 每月的一号1点执行一次
0 0 1 1 1 ? 每年的一月一号的的1点执行一次
使用方式:

直接把表达式替换上去
在这里插入图片描述
难的我也不会 给几个生成cron表达式网址吧
http://cron.qqe2.com/
https://qqe2.com/cron/index
http://www.bejson.com/othertools/cron/

发布了36 篇原创文章 · 获赞 36 · 访问量 9905

猜你喜欢

转载自blog.csdn.net/weixin_43122090/article/details/103587181