当前位置: 代码网 > it编程>编程语言>Java > Springboot如何配置Scheduler定时器

Springboot如何配置Scheduler定时器

2025年03月22日 Java 我要评论
springboot配置scheduler定时器1.在启动类上添加 @enablescheduling 注解开启定时器2.设置定时器任务(间隔和cron表达式都行)package com.exampl

springboot配置scheduler定时器

1.在启动类上添加 @enablescheduling 注解

开启定时器

2.设置定时器任务(间隔和cron表达式都行)

package com.example.springboot01.config;
import org.springframework.scheduling.annotation.scheduled;
import org.springframework.stereotype.component;

@component
public class myscheduler {

    @scheduled(fixedrate = 1000) //每2秒执行一次
    public void statuscheck() {
        system.out.println("【*** a ***】 间隔调度");
    }

    @scheduled(cron="* * * * * ?")  //每秒调用一次
    public void removetohis() {
        try {
            //睡眠3秒
            thread.sleep(3000);
        } catch (interruptedexception e) {
            e.printstacktrace();
        }
        system.out.println("【*** b ***】cron调度");
    }
}

3.配置调度池

package com.example.springboot01.config;
import org.springframework.context.annotation.configuration;
import org.springframework.scheduling.annotation.schedulingconfigurer;
import org.springframework.scheduling.config.scheduledtaskregistrar;
import java.util.concurrent.executors;

/**
 * 用于做并行调度使用
 */
@configuration
public class schedulerconfig implements schedulingconfigurer {

    @override
    public void configuretasks(scheduledtaskregistrar scheduledtaskregistrar) {
        scheduledtaskregistrar.setscheduler(executors.newscheduledthreadpool(100));
    }
}

总结

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

(0)

相关文章:

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

发表评论

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