Springboot实现定时任务

本文介绍了如何在SpringBoot应用中使用定时任务,包括启用定时功能的注解`@EnableScheduling`,创建配置`@Service`类并添加`@Scheduled`注解,以及Cron表达式的详细解释和示例。
摘要由CSDN通过智能技术生成

一、定时任务是什么?

定时执行任务,只有电脑不关机就可以在特定的时间去执行相应的代码,例如抢购脚本等

二、使用步骤

1.无需引入springboot自带

package com.ltx.blog_ltx;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@EnableScheduling //开启定时功能的注解
@SpringBootApplication
public class BlogLtxApplication {
    public static void main(String[] args) {
        SpringApplication.run(BlogLtxApplication.class, args);
    }
}

2.创建配置service类

在配置类上加入:@Service注解

每写一个任务都有加一个    @Scheduled(cron = "") 注解 

package com.example.spingbootswagger.service;
 
 
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
//TaskScheduler 任务调度程序
 
@Service
public class tasksService {
    // 秒 分 时 天 月 周几~
    // 0 * * * * 0-7  每个月的每天每时每分每秒周一到周七都会执行
 
    /**
     * 30 15 10 * * ? 每天10点15分30 执行
     *
     * 30 0/5 10,18 * * ? 每天10时18时每个五分钟执行
     * 0 15 10 ? * 1-6 每个月的周一到周六10.15分钟执行一次
     */
 
    @Scheduled(cron = "0/1 * * * * 0-7")
    public void hello3(){
        System.out.println("每秒打印");
    }
 
    @Scheduled(cron = "0/2 * * * * 0-7")
    public void hello(){
        System.out.println("每隔两秒打印");
    }
 
    @Scheduled(cron = "0/3 * * * * 0-7")
    public void hello1(){
        System.out.println("每个三秒打印");
 
    }
}

3.Cron表达式介绍

Cron表达式是一个具有时间含义的字符串,字符串以5~6个空格隔开,分为6~7个域,格式为X X X X X X X。其中X是一个域的占位符。最后一个代表年份的域非必须,可省略。单个域有多个取值时,使用半角逗号,隔开取值。每个域可以是确定的取值,也可以是具有逻辑意义的特殊字符。每个域最多支持一个前导零。

域取值

    下表为Cron表达式中六、七个域能够取的值以及支持的特殊字符。

 取值示例

     以下为Cron表达式的取值示例。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

用草书谱写兰亭序

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值