Kotlin_协程实现计时器Timer

计时器实现如下,能实现多次计时,如:每2s回到一次 callback

kotlin 复制代码
/**
 * 计时器
 * @property timeOutCallback 计时结束回调
 * @constructor
 */
open class CommonTimer(private val timeOutCallback: (repeatIdex: Int) -> Unit) {
    /**
     * 停止计时
     */
    fun stop() {
        println("momo: call timer stop")
        stoped = true
        job?.cancel()
        job = null
    }

    /**
     * 开始计时
     * @param interval Long 计时间隔
     * @param repeatCount Int 重复次数
     */
    fun start(interval: Long, repeatCount: Int = 1) {
        if (stoped == false) { stop() }
        println("momo: call timer start")
        stoped = false
        job = CoroutineScope(Dispatchers.Default).launch {
            repeat(repeatCount) {
                delay(interval)
                CoroutineScope(Dispatchers.Main).launch {
                    timeOutCallback(it)
                }
                if (stoped) return@repeat
                if (repeatCount - 1 == it) stop()
            }
        }
        job?.start()
    }

    private var job: Job? = null
    private var stoped: Boolean = true
}

使用案例:

kotlin 复制代码
class TimerDemo : ComponentActivity() {
    private val timer = CommonTimer {
        println("momo: timer out $it")
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            Row(
                modifier = Modifier
                    .padding(all = 30.dp)
                    .fillMaxWidth()
                    .height(44.dp),
                horizontalArrangement = Arrangement.SpaceEvenly,
            ) {
                Text(text = "开始计时", modifier = Modifier.clickable {
                    println("momo: click start")
                    timer.start(interval = 2000, repeatCount = 3)
                })
                Text(text = "结束计时", modifier = Modifier.clickable {
                    println("momo: click stop")
                    timer.stop()
                })
            }
        }
    }
}

运行结果:

例1:点击开始后无操作:

kotlin 复制代码
momo: click start
momo: call timer start
momo: timer out 0
momo: timer out 1
momo: timer out 2

例2:点击开始后,回调2次后,点击结束

kotlin 复制代码
momo: click start
momo: call timer start
momo: timer out 0
momo: timer out 1
momo: call timer stop
momo: timer out 2

github demo

相关推荐
前端小伙计2 分钟前
Android/Flutter 项目统一构建配置最佳实践
android·flutter
Mr_sun.2 小时前
Day09——入退管理-入住-2
android·java·开发语言
ujainu3 小时前
告别杂乱!Flutter + OpenHarmony 鸿蒙记事本的标签与分类管理(三)
android·flutter·openharmony
常利兵3 小时前
Android内存泄漏:成因剖析与高效排查实战指南
android
·云扬·3 小时前
MySQL 8.0 Redo Log 归档与禁用实战指南
android·数据库·mysql
野生技术架构师3 小时前
SQL语句性能优化分析及解决方案
android·sql·性能优化
我有与与症4 小时前
从页面加载过程看 Kuikly 的多线程架构
kotlin
doupoa5 小时前
内存指针是什么?为什么指针还要有偏移量?
android·c++
非凡ghost6 小时前
PowerDirector安卓版(威力导演安卓版)
android·windows·学习·软件需求
独行soc6 小时前
2026年渗透测试面试题总结-19(题目+回答)
android·网络·安全·web安全·渗透测试·安全狮