当前位置: 代码网 > it编程>编程语言>Java > SpringBoot项目使用@Scheduled注解实现定时任务的方法

SpringBoot项目使用@Scheduled注解实现定时任务的方法

2025年03月11日 Java 我要评论
springboot项目【使用@scheduled注解实现定时任务】使用springboot创建定时任务目前主要有以下三种创建方式:1、基于注解(@scheduled)- 最简单直接2、基于接口(sc

springboot项目【使用@scheduled注解实现定时任务】

使用springboot创建定时任务目前主要有以下三种创建方式:

1、基于注解(@scheduled)

- 最简单直接
2、基于接口(schedulingconfigurer)

- 适于实际使用中从数据库中读取指定时间来动态执行定时任务
3、基于注解设定多线程定时任务

1. 基于注解(@scheduled)

1.1 @scheduled 注解和 @enablescheduling 注解的使用

基于注解@scheduled默认为单线程,开启多个任务时,任务的执行会受上一个任务执行时间影响

@enablescheduling注解: 在配置类上使用,开启计划任务的支持(类上)。

@scheduled注解: 来声明这是一个任务,包括 cron,fixdelay,fixrate 等类型(方法上,需先开启计划任务的支持)。

【示例】springboot项目中使用@scheduled注解和@enablescheduling注解实现定时任务。

(1)开启定时任务

springboot 项目在项目启动类上添加 @enablescheduling 注解即可开启定时任务管理。

import org.springframework.boot.springapplication;
import org.springframework.boot.autoconfigure.springbootapplication;
import org.springframework.scheduling.annotation.enablescheduling;
@springbootapplication
@enablescheduling //开启定时任务
public class scheduleddemoapplication
{
    public static void main(string[] args)
    {
        springapplication.run(scheduleddemoapplication.class, args);
    }
}

(2)创建定时任务

创建定时任务,并使用 @scheduled 注解。

package com.pjb.schedule;
import org.springframework.scheduling.annotation.scheduled;
import org.springframework.stereotype.component;
import java.text.simpledateformat;
import java.util.date;
/**
 * 定时任务的使用
 * @author pan_junbiao
 **/
@component
public class task
{
    @scheduled(cron="0/5 * *  * * ? ")   //每5秒执行一次
    public void execute(){
        simpledateformat df = new simpledateformat("yyyy-mm-dd hh:mm:ss"); //设置日期格式
        system.out.println("欢迎访问 pan_junbiao的博客 " + df.format(new date()));
    }
}

1.2 @scheduled 注解各参数讲解

@scheduled 注解具有多个参数,以下是常用的几个参数:

cron

接收一个 cron 表达式。cron 表达式由六个或七个域组成,常见的格式如下:

css
复制编辑
[秒] [分] [小时] [日] [月] [周] [年]

序号说明是否必填允许填写的值允许的通配符
10-59, - * /
20-59, - * /
3小时0-23, - * /
41-31, - * ? / l w
51-12 or jan-dec, - * /
61-7 or sun-sat, - * ? / l #
7空或1970-2099, - * /

通配符说明:

? 表示不指定值。使用的场景为不需要关心当前设置这个字段的值。例如:要在每月的10号触发一个操作,但不关心是周几,所以需要周位置的那个字段设置为"?" 具体设置为 0 0 0 10 * ?

-表示区间。例如 在小时上设置 “10-12”,表示 10,11,12点都会触发。

, 表示指定多个值,例如在周字段上设置 “mon,wed,fri” 表示周一,周三和周五触发

/ 用于递增触发。如在秒上面设置"5/15" 表示从5秒开始,每增15秒触发(5,20,35,50)。在月字段上设置’1/3’所示每月1号开始,每隔三天触发一次。

l 表示最后的意思。在日字段设置上,表示当月的最后一天(依据当前月份,如果是二月还会依据是否是润年[leap]), 在周字段上表示星期六,相当于"7"或"sat"。如果在"l"前加上数字,则表示该数据的最后一个。例如在周字段上设置"6l"这样的格式,则表示“本月最后一个星期五"

w 表示离指定日期的最近那个工作日(周一至周五). 例如在日字段上设置"15w",表示离每月15号最近的那个工作日触发。(注,“w"前只能设置具体的数字,不允许区间”-")

常用示例:

定时任务表达式描述
0 0 12 * * ?每天12点触发
0 15 10 ? * *每天10点15分触发
0 15 10 * * ?每天10点15分触发
0 15 10 * * ? *每天10点15分触发
0 15 10 * * ? 20252025年每天10点15分触发
0 * 14 * * ?每天下午的 2点到2点59分每分触发
0 0/5 14 * * ?每天下午的 2点到2点59分(整点开始,每隔5分触发)
0 0/5 14,18 * * ?每天下午的 2点到2点59分(整点开始,每隔5分触发)每天下午的 18点到18点59分(整点开始,每隔5分触发)
0 0-5 14 * * ?每天下午的 2点到2点05分每分触发
0 10,44 14 ? 3 wed3月分每周三下午的 2点10分和2点44分触发
0 15 10 ? * mon-fri从周一到周五每天上午的10点15分触发
0 15 10 15 * ?每月15号上午10点15分触发
0 15 10 l * ?每月最后一天的10点15分触发
0 15 10 ? * 6l每月最后一周的星期五的10点15分触发
0 15 10 ? * 6l 2022-2025从2022年到2025年每月最后一周的星期五的10点15分触发
0 15 10 ? * 6#3每月的第三周的星期五开始触发
0 0 12 1/5 * ?每月的第一个中午开始每隔5天触发一次
0 11 11 11 11 ?每年的11月11号 11点11分触发(光棍节)

其他常用

  • fixeddelay: 上次任务完成后多少毫秒再执行。
  • fixedrate: 上次任务开始后多少毫秒再执行。
  • initialdelay: 第一次延迟多少毫秒后再执行。

2. 动态定时任务:基于接口(schedulingconfigurer)

2.1 创建数据库表

在 mysql 数据库中创建一个 cron 表,存储定时任务的 cron 表达式:

drop table if exists cron;
create table cron (
    cron_id varchar(30) not null primary key,
    cron varchar(30) not null
);
insert into cron values ('1', '0/5 * * * * ?');

2.2 添加 mybatis 依赖

pom.xml 中添加 mybatis 和 mysql 的 jdbc 依赖:

<!-- mybatis与springboot整合依赖 -->
<dependency>
    <groupid>org.mybatis.spring.boot</groupid>
    <artifactid>mybatis-spring-boot-starter</artifactid>
    <version>2.1.3</version>
</dependency>
<!-- mysql的jdbc数据库驱动 -->
<dependency>
    <groupid>mysql</groupid>
    <artifactid>mysql-connector-java</artifactid>
    <version>8.0.20</version>
</dependency>

2.3 创建定时任务配置类

package com.pjb.config;
import org.apache.ibatis.annotations.mapper;
import org.apache.ibatis.annotations.select;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.context.annotation.configuration;
import org.springframework.scheduling.annotation.enablescheduling;
import org.springframework.scheduling.annotation.schedulingconfigurer;
import org.springframework.scheduling.config.scheduledtaskregistrar;
import org.springframework.scheduling.support.crontrigger;
import org.springframework.util.stringutils;
import java.time.localdatetime;
/**
 * 动态定时任务配置类
 * @author pan_junbiao
 **/
@configuration
@enablescheduling
public class dynamicscheduleconfigurer implements schedulingconfigurer {
    @mapper
    public interface cronmapper {
        @select("select cron from cron limit 1")
        public string getcron();
    }
    @autowired
    cronmapper cronmapper;
    @override
    public void configuretasks(scheduledtaskregistrar taskregistrar) {
        taskregistrar.addtriggertask(
                () -> system.out.println("欢迎访问 pan_junbiao的博客: " + localdatetime.now().tolocaltime()),
                triggercontext -> {
                    string cron = cronmapper.getcron();
                    if (stringutils.isempty(cron)) {
                        // 错误处理
                    }
                    return new crontrigger(cron).nextexecutiontime(triggercontext);
                }
        );
    }
}

3. 基于注解设定多线程定时任务

通过 @async 注解开启多线程定时任务,解决多个任务执行时相互影响的问题。

创建多线程定时任务

package com.pjb.task;
import org.springframework.scheduling.annotation.async;
import org.springframework.scheduling.annotation.enableasync;
import org.springframework.scheduling.annotation.enablescheduling;
import org.springframework.scheduling.annotation.scheduled;
import org.springframework.stereotype.component;
import java.time.localdatetime;
/**
 * 基于注解设定多线程定时任务
 * @author pan_junbiao
 */
@component
@enablescheduling   // 开启定时任务
@enableasync        // 开启多线程
public class multithreadscheduletask {
    @async
    @scheduled(fixeddelay = 1000)  // 间隔1秒
    public void first() throws interruptedexception {
        system.out.println("第一个定时任务开始 : " + localdatetime.now().tolocaltime() + "\r\n线程 : " + thread.currentthread().getname());
        thread.sleep(1000 * 10);
    }
    @async
    @scheduled(fixeddelay = 2000)
    public void second() {
        system.out.println("第二个定时任务开始 : " + localdatetime.now().tolocaltime() + "\r\n线程 : " + thread.currentthread().getname());
    }
}

注意

由于 @scheduled 默认是单线程模式,开启多个定时任务时任务的执行顺序会受前一个任务的执行时间影响。通过 @async 注解,我们可以解决这个问题,使多个定时任务并行执行。

通过以上三种方式,spring boot 提供了灵活的定时任务支持,可以根据项目需求选择合适的实现方式。

到此这篇关于springboot项目使用@scheduled注解实现定时任务的文章就介绍到这了,更多相关springboot @scheduled定时任务内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com