You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现延迟10秒后重复执行suspend函数?

实现延迟10秒重复执行挂起函数的方案

有两种简单直接的方案可以实现需求,以下是具体代码实现:

方式一:while循环+delay

直接在协程内通过循环控制重复逻辑,每次执行后延迟10秒:

suspend fun ethPriceRequestFun(): Double { 
    // 你的请求逻辑实现
    return 21000.0 // 示例返回值
}

fun callRequest() = runBlocking {
    // 无限重复执行,需停止可添加布尔条件控制
    while (true) {
        val ethPrice = ethPriceRequestFun()
        println("当前ETH价格:$ethPrice")
        delay(10000) // 延迟10秒(单位为毫秒)
    }
}

如果需要支持主动停止,可引入原子变量控制循环:

import java.util.concurrent.atomic.AtomicBoolean

fun callRequest(isRunning: AtomicBoolean = AtomicBoolean(true)) = runBlocking {
    while (isRunning.get()) {
        val ethPrice = ethPriceRequestFun()
        println("当前ETH价格:$ethPrice")
        delay(10000)
    }
}

// 停止时调用 isRunning.set(false)

方式二:使用Flow.interval

借助Kotlin Flow的定时操作符实现响应式的重复执行:

import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.interval
import kotlin.time.Duration.Companion.seconds

suspend fun ethPriceRequestFun(): Double { 
    // 你的请求逻辑实现
    return 21000.0
}

fun callRequest() = runBlocking {
    interval(10.seconds).collect {
        val ethPrice = ethPriceRequestFun()
        println("当前ETH价格:$ethPrice")
    }
}

若要支持停止,可将Flow收集逻辑放在独立协程中,通过Job控制:

import kotlinx.coroutines.launch

fun callRequest() = runBlocking {
    val job = launch {
        interval(10.seconds).collect {
            val ethPrice = ethPriceRequestFun()
            println("当前ETH价格:$ethPrice")
        }
    }
    // 需要停止时调用 job.cancel()
}

注意:runBlocking会阻塞调用线程,若在Android等平台开发,建议使用viewModelScope、lifecycleScope这类绑定生命周期的协程作用域替代。

内容的提问来源于stack exchange,提问作者lizabethfrank

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 06:20:28