Commit 29fa5e2b by patpat

增加TimerHelper

parent 9b326807
package com.bgycc.smartcanteen.helper
import android.util.Log
import android.util.LongSparseArray
import java.lang.Exception
import java.util.concurrent.Executors
import java.util.concurrent.ScheduledFuture
import java.util.concurrent.TimeUnit
object TimerHelper {
val TAG = TimerHelper::class.java.simpleName
private var mId: Long = 0L
get() = ++field
private val mScheduledExecutorService = Executors.newScheduledThreadPool(3)
private val mFutureList = LongSparseArray<ScheduledFuture<*>>()
fun shutdown() {
mFutureList.clear()
mScheduledExecutorService.shutdown()
}
@Synchronized fun cancel(id: Long) {
try {
val future = mFutureList.get(id) ?: return
mFutureList.remove(id)
future.cancel(true)
} catch (e: Exception) {}
}
fun timeout(runnable: () -> Unit, time: Long): Long {
val id = mId
mFutureList.put(id, mScheduledExecutorService.schedule({
mFutureList.remove(id)
runnable()
}, time, TimeUnit.MILLISECONDS))
return id
}
fun loop(runnable: (id: Long) -> Boolean, period: Long, times: Int = -1): Long {
val id = mId
mFutureList.put(id, mScheduledExecutorService.scheduleWithFixedDelay(object: Runnable {
var vTimes = 0
override fun run() {
if (times >= 0) {
vTimes++
if (vTimes > times) {
cancel(id)
return
}
}
if (!runnable(id)) {
cancel(id)
}
}
}, 0, period, TimeUnit.MILLISECONDS))
return id
}
fun test() {
Log.i(TAG, "start")
timeout({
Log.i(TAG, "timeout")
}, 1000)
loop({
Log.i(TAG, "loop")
return@loop true
}, 1000, 4)
}
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment