优化
This commit is contained in:
@@ -15,6 +15,7 @@ class IntervalExecutor {
|
||||
fun startIntervalTask(delayMillis: Long, action: suspend () -> Unit): Job {
|
||||
return CoroutineScope(Dispatchers.Default).launch {
|
||||
while (isActive) {
|
||||
ensureActive()
|
||||
action()
|
||||
delay(delayMillis)
|
||||
}
|
||||
@@ -36,6 +37,7 @@ class IntervalExecutor {
|
||||
return CoroutineScope(Dispatchers.Default).launch {
|
||||
delay(initialDelay)
|
||||
while (isActive) {
|
||||
ensureActive()
|
||||
action()
|
||||
delay(delayMillis)
|
||||
}
|
||||
@@ -44,23 +46,23 @@ class IntervalExecutor {
|
||||
}
|
||||
|
||||
// 使用示例
|
||||
fun main() = runBlocking {
|
||||
val executor = IntervalExecutor()
|
||||
|
||||
// 示例1:每隔10秒执行一次
|
||||
val job1 = executor.startIntervalTask(10000) {
|
||||
println("定时任务执行: ${System.currentTimeMillis()}")
|
||||
// 这里可以执行你的业务逻辑
|
||||
}
|
||||
|
||||
// 示例2:先延迟5秒,然后每隔3秒执行一次
|
||||
val job2 = executor.startIntervalTaskWithInitialDelay(5000, 3000) {
|
||||
println("带初始延迟的定时任务: ${System.currentTimeMillis()}")
|
||||
}
|
||||
|
||||
// 运行30秒后取消任务
|
||||
delay(30000)
|
||||
job1.cancel()
|
||||
job2.cancel()
|
||||
println("所有定时任务已取消")
|
||||
}
|
||||
//fun main() = runBlocking {
|
||||
// val executor = IntervalExecutor()
|
||||
//
|
||||
// // 示例1:每隔10秒执行一次
|
||||
// val job1 = executor.startIntervalTask(10000) {
|
||||
// println("定时任务执行: ${System.currentTimeMillis()}")
|
||||
// // 这里可以执行你的业务逻辑
|
||||
// }
|
||||
//
|
||||
// // 示例2:先延迟5秒,然后每隔3秒执行一次
|
||||
// val job2 = executor.startIntervalTaskWithInitialDelay(5000, 3000) {
|
||||
// println("带初始延迟的定时任务: ${System.currentTimeMillis()}")
|
||||
// }
|
||||
//
|
||||
// // 运行30秒后取消任务
|
||||
// delay(30000)
|
||||
// job1.cancel()
|
||||
// job2.cancel()
|
||||
// println("所有定时任务已取消")
|
||||
//}
|
||||
Reference in New Issue
Block a user