基于Spring实现类似调度器或监控

场景:定时任务调度,实时监控

实现:基于两个类实现,如下:

package com.demo;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

/**
 * 配置类
 */
@Component
public class TestC implements InitializingBean {

    @Override
    public void afterPropertiesSet() throws Exception {
        TestR runT = new TestR();
        runT.run();
    }
}
package com.demo;

/**
 * 运行类
 */
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class TestR {

    public void run() {
        Thread newThread = new Thread() {
            @Override
            public void run() {


                while (true) {
                    try {
                        sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    log.info("hello world~~~~~~~~~~~~~~~~~~~~~");
                    System.out.println("hello world");
                }
            }
        };
        newThread.start();
    }
}

控制台打印如下 

2023-05-26 13:29:44 INFO Thread-14 com.jack.RunT hello world~~~~~~~~~~~~~~~~~~~~~
hello world
2023-05-26 13:29:49 INFO Thread-14 com.jack.RunT hello world~~~~~~~~~~~~~~~~~~~~~
hello world
2023-05-26 13:29:54 INFO Thread-14 com.jack.RunT hello world~~~~~~~~~~~~~~~~~~~~~
hello world
2023-05-26 13:29:59 INFO Thread-14 com.jack.RunT hello world~~~~~~~~~~~~~~~~~~~~~
hello world

总结:Spring容器中注入一个组件TestC且组件自定义初始化逻辑,初始化逻辑中调用另一个类TestR的方法,该方法中创建一个线程并运行。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值