All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.spring.boxes.dollar.StopWatchUtils Maven / Gradle / Ivy

package com.spring.boxes.dollar;

import com.spring.boxes.dollar.enums.TimeUnitEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.StopWatch;

import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;

@Slf4j
public class StopWatchUtils {

    public static  R timeConsume(Function task, T param, String taskName) {
        return timeConsume(task, param, taskName, TimeUnit.MILLISECONDS, true);
    }

    public static  R timeConsume(Function task, T param, String taskName, TimeUnit timeUnit) {
        return timeConsume(task, param, taskName, timeUnit, true);
    }

    public static  R timeConsume(Function task, T param, String taskName, TimeUnit timeUnit, boolean enablePrint) {
        if (!enablePrint) {
            return task.apply(param);
        }
        StopWatch stopWatch = StopWatch.createStarted();
        try {
            return task.apply(param);
        } finally {
            loggerConsole(taskName, stopWatch, timeUnit);
        }
    }

    public static  void timeConsume(Consumer task, T param, String taskName) {
        timeConsume(task, param, taskName, TimeUnit.MILLISECONDS, true);
    }

    public static  void timeConsume(Consumer task, T param, String taskName, TimeUnit timeUnit) {
        timeConsume(task, param, taskName, timeUnit, true);
    }

    public static  void timeConsume(Consumer task, T param, String taskName, TimeUnit timeUnit, boolean enablePrint) {
        if (!enablePrint) {
            task.accept(param);
            return;
        }
        StopWatch stopWatch = StopWatch.createStarted();
        try {
            task.accept(param);
        } finally {
            loggerConsole(taskName, stopWatch, timeUnit);
        }
    }

    public static  R timeConsume(Supplier task, String taskName) {
        return timeConsume(task, taskName, TimeUnit.MILLISECONDS, true);
    }

    public static  R timeConsume(Supplier task, String taskName, TimeUnit timeUnit) {
        return timeConsume(task, taskName, timeUnit, true);
    }

    public static  R timeConsume(Supplier task, String taskName, TimeUnit timeUnit, boolean enablePrint) {
        if (!enablePrint) {
            return task.get();
        }
        StopWatch stopWatch = StopWatch.createStarted();
        try {
            return task.get();
        } finally {
            loggerConsole(taskName, stopWatch, timeUnit);
        }
    }

    private static void loggerConsole(String taskName, StopWatch stopWatch, TimeUnit timeUnit) {
        log.info("[StopWatch] 操作: {}, 耗时: {}{}", taskName, stopWatch.getTime(timeUnit), TimeUnitEnum.getUnitAbbreviation(timeUnit));
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy