This commit is contained in:
mazengfei
2026-01-20 14:00:28 +08:00
parent ec12017fd4
commit b7408dc6c4
3 changed files with 147 additions and 99 deletions
@@ -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("所有定时任务已取消")
//}