TimerWatch计时器

计时器,相比于 原生的 不会抛出任何异常
非常适合job类处理,计算每个过程数量及耗时

定义
@NotThreadSafe
public class TimerWatch extends StopWatch {
    private final String watchName;
    private Integer totalCount;
    // 是否记录观察子任务
    private boolean keepTaskList = true;

    public void setKeepTaskList(boolean keepTaskList) {
        super.setKeepTaskList(keepTaskList);
        this.keepTaskList = keepTaskList;
    }

    public void setTotalCount(Integer totalCount) {
        this.totalCount = totalCount;
    }

    public TimerWatch() {
        super("");
        this.watchName = "";
    }

    // 观察命名
    public TimerWatch(String watchName) {
        super(watchName);
        this.watchName = watchName;
    }

    // 开启观察任务命名
    @Override
    public void start(String taskName) {
        try {
            if (isRunning()) {
                super.stop();
            }
            super.start(taskName);
        } catch (Exception e) {

        }
    }


    @Override
    public void start() {
        try {
            if (isRunning()) {
                super.stop();
            }
            super.start("");
        } catch (Exception e) {

        }
    }

    // 结束观察
    @Override
    public void stop() {
        try {
            if (isRunning()) {
                super.stop();
            }
        } catch (Exception e) {

        }
    }


    public String prettyLog() {
        StringBuilder sb = new StringBuilder("StopWatch");
        if (watchName != null) {
            sb.append(" watchName:").append(watchName);
        }
        if (totalCount != null) {
            sb.append(" totalCount:").append(totalCount);
        }
        sb.append(" totalConst:").append(getTotalTimeMillis()).append("ms");
        try {
            if (keepTaskList) {
                for (StopWatch.TaskInfo task : getTaskInfo()) {
                    long percent = Math.round(100.0 * task.getTimeMillis() / getTotalTimeMillis());
                    sb.append("; [").append(task.getTaskName()).append(" const:").append(task.getTimeMillis()).append("ms").append(" percent:").append(percent).append("% ]");
                }
            }
        } catch (Exception e) {

        }

        return sb.toString();
    }


}
使用示例

在这里插入图片描述

日志打印结果

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值