当前位置: 代码网 > it编程>编程语言>Java > @Scheduled在springboot中的使用方式

@Scheduled在springboot中的使用方式

2024年08月02日 Java 我要评论
@scheduled注解参数cron:cron表达式,指定任务在特定时间执行;fixeddelay:表示上一次任务执行完成后多久再次执行,参数类型为long,单位ms;fixeddelaystring

@scheduled注解参数

  • cron:cron表达式,指定任务在特定时间执行;
  • fixeddelay:表示上一次任务执行完成后多久再次执行,参数类型为long,单位ms;
  • fixeddelaystring:与fixeddelay含义一样,只是参数类型变为string;
  • fixedrate:表示按一定的频率执行任务,参数类型为long,单位ms;
  • fixedratestring: 与fixedrate的含义一样,只是将参数类型变为string;
  • initialdelay:表示延迟多久再第一次执行任务,参数类型为long,单位ms;
  • initialdelaystring:与initialdelay的含义一样,只是将参数类型变为string;
  • zone:时区,默认为当前时区。

cron表达式语法

[秒] [分] [小时] [日] [月] [周] [年]

序号说明必填允许填写的值允许的通配符
10-59, - * /
20-59, - * /
30-23, - * /
41-31, - * ? / l w
51-12 / jan-dec, - * /
61-7 or sun-sat, - * ? / l #
71970-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号开始,每隔三天触发一次。(/后边的参数如果循环到下一个循环是不会执行的,只会在当前循环中去循环,如:1/58->会在1、59秒执行,但1/59->则只会在1秒的时候执行,不会跳到下一个循环去执行的)
  • l 表示最后的意思。在日字段设置上,表示当月的最后一天(依据当前月份,如果是二月还会依据是否是润年[leap]), 在周字段上表示星期六,相当于”7”或”sat”。如果在”l”前加上数字,则表示该数据的最后一个。例如在周字段上设置”6l”这样的格式,则表示“本月最后一个星期五”
  • w 表示离指定日期的最近那个工作日(周一至周五). 例如在日字段上置”15w”,表示离每月15号最近的那个工作日触发。如果15号正好是周六,则找最近的周五(14号)触发, 如果15号是周未,则找最近的下周一(16号)触发.如果15号正好在工作日(周一至周五),则就在该天触发。如果指定格式为 “1w”,它则表示每月1号往后最近的工作日触发。如果1号正是周六,则将在3号下周一触发。(注,”w”前只能设置具体的数字,不允许区间”-“)。
  • # 序号(表示每月的第几个周几),例如在周字段上设置”6#3”表示在每月的第三个周六.注意如果指定”#5”,正好第五周没有周六,则不会触发该配置(用在母亲节和父亲节再合适不过了) ;小提示:’l’和 ‘w’可以一组合使用。如果在日字段上设置”lw”,则表示在本月的最后一个工作日触发;周字段的设置,若使用英文字母是不区分大小写的,即mon与mon相同。

1. 示例

  • 每隔5秒执行一次:*/5 * * * * ?
  • 每隔1分钟执行一次:0 */1 * * * ?
  • 每天23点执行一次:0 0 23 * * ?
  • 每天凌晨1点执行一次:0 0 1 * * ?
  • 每月1号凌晨1点执行一次:0 0 1 1 * ?
  • 每月最后一天23点执行一次:0 0 23 l * ?
  • 每周星期六凌晨1点实行一次:0 0 1 ? * l
  • 在26分、29分、33分执行一次:0 26,29,33 * * * ?
  • 每天的0点、13点、18点、21点都执行一次:0 0 0,13,18,21 * * ?

2. zone

时区,接收一个java.util.timezone#id

cron表达式会基于该时区解析。

默认是一个空字符串,即取服务器所在地的时区。

比如我们一般使用的时区asia/shanghai。该字段我们一般留空。

3. fixeddelay

上一次执行完毕时间点之后多长时间再执行。

如:

@scheduled(fixeddelay = 5000) //上一次执行完毕时间点之后5秒再执行

4. fixeddelaystring

3.fixeddelay 意思相同,只是使用字符串的形式。

唯一不同的是支持占位符。

如:

@scheduled(fixeddelaystring = "5000") //上一次执行完毕时间点之后5秒再执行

占位符的使用(配置文件中有配置:time.fixeddelay=5000):

    @scheduled(fixeddelaystring = "${time.fixeddelay}")
    void testfixeddelaystring() {
        system.out.println("execute at " + system.currenttimemillis());
    }

运行结果:

占位符的使用

5. fixedrate

上一次开始执行时间点之后多长时间再执行。

如:

@scheduled(fixedrate = 5000) //上一次开始执行时间点之后5秒再执行

6. fixedratestring

5.fixedrate 意思相同,只是使用字符串的形式。

唯一不同的是支持占位符。

7. initialdelay

第一次延迟多长时间后再执行。

如:

@scheduled(initialdelay=1000, fixedrate=5000) //第一次延迟1秒后执行,之后按fixedrate的规则每5秒执行一次

8. initialdelaystring

7.initialdelay 意思相同,只是使用字符串的形式。唯一不同的是支持占位符。

that's all ! thanks for reading.

另外如果要想@scheduled注解生效需要添加配置

package com.example.demo;

import lombok.extern.slf4j.slf4j;
import org.springframework.aop.interceptor.asyncuncaughtexceptionhandler;
import org.springframework.aop.interceptor.simpleasyncuncaughtexceptionhandler;
import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.configuration;
import org.springframework.scheduling.taskscheduler;
import org.springframework.scheduling.annotation.asyncconfigurer;
import org.springframework.scheduling.annotation.enableasync;
import org.springframework.scheduling.annotation.enablescheduling;
import org.springframework.scheduling.annotation.schedulingconfigurer;
import org.springframework.scheduling.concurrent.threadpooltaskexecutor;
import org.springframework.scheduling.concurrent.threadpooltaskscheduler;
import org.springframework.scheduling.config.scheduledtaskregistrar;

import java.util.concurrent.executor;
import java.util.concurrent.executors;
import java.util.concurrent.threadpoolexecutor;


/**
 * 在用springboot框架做定时任务的时候,大部分情况都是直接通过@scheduled注解来指定定时任务的。
 * 但是当你有多个定时任务时,@scheduled并不一定会按时执行。
 * 因为使用@scheduled的定时任务虽然是异步执行的,但是,默认不同的定时任务之间并不是并行的。
 *
 * 当未手动指定taskscheduler时,会通过executors.newsinglethreadscheduledexecutor()创建默认的单线程线程池,
 * 且该线程池的拒绝策略为abortpolicy,这种策略在线程池无可用线程时丢弃任务,
 * 并抛出异常rejectedexecutionexception。
 *
 */
@slf4j
@configuration
@enablescheduling
@enableasync
public class scheduledconfig implements
        schedulingconfigurer
//        , asyncconfigurer
{


    /**
     * threadpooltaskexecutor是一个专门用于执行任务的类。
     * threadpooltaskscheduler是一个专门用于调度任务的类。
     * 一个threadpooltaskexecutor通过它的corepoolsize , maxpoolsize , keepaliveseconds和queuecapacity属性在线程池中提供细粒度的配置。
     * 诸如threadpooltaskscheduler这样的调度器不提供这样的配置。
     */


    /** 最大线程数 */
    private static final int maxpoolsize = 10;
    /** 线程池名前缀(字符串有长度限制) */
    private static final string threadnameprefix = "yu-scheduled-";

    @bean("asyncexecutorscheduled") // bean的名称,默认为首字母小写的方法名,如果不声明则会使用方法名
    public threadpooltaskscheduler asyncexecutorscheduled(){
        threadpooltaskscheduler executor = new threadpooltaskscheduler();
        executor.setpoolsize(maxpoolsize);
        executor.setthreadnameprefix(threadnameprefix);
        executor.setawaitterminationseconds(60);
        executor.setwaitfortaskstocompleteonshutdown(true);
        // 初始化
        executor.initialize();
        return executor;
    }

    @override
    public void configuretasks(scheduledtaskregistrar taskregistrar) {
        taskregistrar.settaskscheduler(this.asyncexecutorscheduled());
    }

//    /**
//     * 处理异步方法调用时要使用的实例
//     * @return
//     */
//    @override
//    public executor getasyncexecutor() {
//        return this.asyncexecutorscheduled();
//    }
//
//    /**
//     * 在使用void返回类型的异步方法执行期间抛出异常时要使用的实例。
//     * @return
//     */
//    @override
//    public asyncuncaughtexceptionhandler getasyncuncaughtexceptionhandler() {
//        return new simpleasyncuncaughtexceptionhandler();
//    }
}

或者:

package com.example.demo;

import lombok.extern.slf4j.slf4j;
import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.configuration;
import org.springframework.scheduling.annotation.enablescheduling;

import java.util.concurrent.scheduledthreadpoolexecutor;


/**
 * scheduled 配置文件的第二种使用  不建议使用
 */
@slf4j
@configuration
@enablescheduling
public class scheduledconfig2 {



    @bean
    public scheduledthreadpoolexecutor scheduledexecutorservice() {
        scheduledthreadpoolexecutor executor = new scheduledthreadpoolexecutor(10);
        return executor;
    }


}

实例:

package com.example.demo.service;

import lombok.extern.slf4j.slf4j;
import org.springframework.scheduling.annotation.scheduled;
import org.springframework.stereotype.service;

import java.util.date;

/**
 * @scehduled 定时任务测试
 */
@slf4j
@service
public class scheduledservice {
    /**5
     *测试
     */
    @scheduled(cron = "*/5 * * * * *")
    public void testscheduled1(){
        log.info("定时1:{}",new date());
    }

    @scheduled(cron = "*/5 * * * * *")
    public void testscheduled2(){
        log.info("定时2:{}",new date());
    }

}

结果:

2020-05-25 16:36:00.001  info 9116 --- [ yu-scheduled-1] c.example.demo.service.scheduledservice  : 定时2:mon may 25 16:36:00 cst 2020
2020-05-25 16:36:00.005  info 9116 --- [ yu-scheduled-2] c.example.demo.service.scheduledservice  : 定时1:mon may 25 16:36:00 cst 2020
2020-05-25 16:36:05.004  info 9116 --- [ yu-scheduled-1] c.example.demo.service.scheduledservice  : 定时2:mon may 25 16:36:05 cst 2020
2020-05-25 16:36:05.004  info 9116 --- [ yu-scheduled-2] c.example.demo.service.scheduledservice  : 定时1:mon may 25 16:36:05 cst 2020

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。

(0)

相关文章:

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

发表评论

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