节流工具,避免操作太频繁

ThrottleUtil

用于保证某个操作在一定时间内只执行一次的工具。

java 复制代码
package com.cashpro.kash.lending.loan.utils;

/**
 * <pre>
 * Created by zhuguohui
 * Date: 2024/6/26
 * Time: 13:43
 * Desc:用于节流执行任务,限制任务执行的频次
 * </pre>
 */

import android.os.Handler;

import java.util.HashMap;
import java.util.Map;

public class ThrottleUtil {

    private static final Handler HANDLER = new Handler();


    private static Map<String, Long> lastExecutionTimeMap = new HashMap<>();
    private static Map<String, Runnable> runnableMap = new HashMap<>();

    /**
     * 执行节流操作,确保操作在连续触发后至少等待指定的时间间隔再执行。
     *
     * @param opName         要执行操作的名称
     * @param intervalMillis 时间间隔,以毫秒为单位
     * @param runnable       要执行的操作
     */
    public static synchronized void executeThrottled(String opName, long intervalMillis, Runnable runnable) {
        long currentTime = System.currentTimeMillis();
        long lastExecutionTime = 0;
        if (lastExecutionTimeMap.containsKey(opName)) {
            Long aLong = lastExecutionTimeMap.get(opName);
            if (aLong != null) {
                lastExecutionTime = aLong;
            }
        }


        // 如果距离上次执行已经超过指定时间间隔,则立即执行操作
        if (currentTime - lastExecutionTime >= intervalMillis) {
            runnable.run();
            lastExecutionTime = currentTime;
            lastExecutionTimeMap.put(opName, lastExecutionTime);
        } else {
            // 如果时间未到,则移除之前的Runnable并重新添加
            Runnable throttleRunnable = runnableMap.get(opName);
            if (throttleRunnable != null) {
                HANDLER.removeCallbacks(throttleRunnable);
                runnableMap.remove(opName);
            }
            throttleRunnable = () -> {
                runnable.run();
                long lastExecutionTime1 = System.currentTimeMillis();
                lastExecutionTimeMap.put(opName, lastExecutionTime1);
                runnableMap.remove(opName);
            };
            runnableMap.put(opName, throttleRunnable);
            HANDLER.postDelayed(throttleRunnable, intervalMillis - (currentTime - lastExecutionTime));
        }
    }

    // 工具类不需要实例化,所以构造器私有
    private ThrottleUtil() {
        // 阻止实例化
    }

    // 可以在Activity或Fragment的onDestroy()中调用此方法,以确保没有内存泄漏
    public static void clearCallbacks(String... opNames) {
        for (String opName : opNames) {
            Runnable runnable = runnableMap.get(opName);
            if (runnable != null) {
                HANDLER.removeCallbacks(runnable);
            }
            runnableMap.remove(opName);
        }

    }
}

使用

如下使用,其中第一个参数是一个操作名称,每个界面的操作不能重复。否则可能被其他地方取消。

按时取消

在界面销毁的时候记得移除操作

相关推荐
Coder_Boy_7 小时前
技术让开发更轻松的底层矛盾
java·大数据·数据库·人工智能·深度学习
2501_944934737 小时前
高职大数据技术专业,CDA和Python认证优先考哪个?
大数据·开发语言·python
玉梅小洋7 小时前
Windows 10 Android 构建配置指南
android·windows
invicinble7 小时前
对tomcat的提供的功能与底层拓扑结构与实现机制的理解
java·tomcat
较真的菜鸟7 小时前
使用ASM和agent监控属性变化
java
黎雁·泠崖7 小时前
【魔法森林冒险】5/14 Allen类(三):任务进度与状态管理
java·开发语言
2301_763472468 小时前
C++20概念(Concepts)入门指南
开发语言·c++·算法
Libraeking8 小时前
视觉篇:Canvas 自定义绘图与高级动画的华丽圆舞曲
android·经验分享·android jetpack
TechWJ9 小时前
PyPTO编程范式深度解读:让NPU开发像写Python一样简单
开发语言·python·cann·pypto
qq_12498707539 小时前
基于SSM的动物保护系统的设计与实现(源码+论文+部署+安装)
java·数据库·spring boot·毕业设计·ssm·计算机毕业设计