这有可能从完整的分钟开始每分钟在android中执行功能吗,例如。当我在8:30:12运行我的应用程序时,第一个函数调用将在8:31:00,然后在8:32:00,依此类推。
您必须首先计算在8:30:12开始执行任务所需的精确到分钟的时间,第一次调用应该在8:31:00进行。
因此,您可以使用提取当前时间System.currentTimeMillis()
,然后将其分钟数取整为最接近的整数,
// import kotlin.math.ceil
val firstCallTime = ceil(System.currentTimeMillis() / 60_000.0).toLong() * 60_000
然后,您可以使用协程来处理您的任务,该任务将使用CommonPool从中获取可重用的线程,并且不需要您创建线程。
// scope can be anything, for instance you want to call the function
// only when client is using your application then use viewModelScope provided,
// otherwise your own scope like `val scope = CoroutineScope(Dispatchers.Main)`
// Or use Dispatchers.Default for CPU intensive tasks
val parentJob = scope.launch {
// suspend till first minute comes after some seconds
delay(firstCallTime - System.currentTimeMillis())
while (true) {
launch {
yourFunctionToBeCalled()
}
delay(60_000) // 1 minute delay (suspending)
}
}
// If you ever want your job to cancel just do a cancel,
// the function delay suspends and so cancellable without interrupting the threads
// parentJob.cancel()
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句