main.com.wisetrack.sdk.scheduler.SingleThreadFutureScheduler.kt Maven / Gradle / Ivy
package com.wisetrack.sdk.scheduler
import com.wisetrack.sdk.WiseTrackFactory
import java.util.concurrent.Callable
import java.util.concurrent.ScheduledFuture
import java.util.concurrent.ScheduledThreadPoolExecutor
import java.util.concurrent.TimeUnit
/**
@author hamed (@hamed-hsb)
* @since 09th October 2021
*/
class SingleThreadFutureScheduler(source: String, doKeepAlive: Boolean) : FutureScheduler {
private var scheduledThreadPoolExecutor: ScheduledThreadPoolExecutor? = null
init {
scheduledThreadPoolExecutor = ScheduledThreadPoolExecutor(
1,
ThreadFactoryWrapper(source),
{ runnable, _ ->
// Logs rejected runnable rejected from the entering the pool
WiseTrackFactory.getLogger().warn(
"Runnable [${runnable}] rejected from [$source] "
)
}
)
if (!doKeepAlive) {
scheduledThreadPoolExecutor!!.setKeepAliveTime(10L, TimeUnit.MILLISECONDS)
scheduledThreadPoolExecutor!!.allowCoreThreadTimeOut(true)
}
}
override fun scheduleFuture(command: Runnable?, millisecondDelay: Long): ScheduledFuture<*>? {
return scheduledThreadPoolExecutor!!.schedule(
RunnableWrapper(command),
millisecondDelay,
TimeUnit.MILLISECONDS
)
}
override fun scheduleFutureWithFixedDelay(
command: Runnable?,
initialMillisecondDelay: Long,
millisecondDelay: Long
): ScheduledFuture<*>? {
return scheduledThreadPoolExecutor!!.scheduleWithFixedDelay(
RunnableWrapper(command),
initialMillisecondDelay,
millisecondDelay,
TimeUnit.MILLISECONDS
)
}
override fun scheduleFutureWithReturn(
callable: Callable?,
millisecondDelay: Long
): ScheduledFuture? {
return scheduledThreadPoolExecutor!!.schedule(Callable {
try {
return@Callable callable!!.call()
} catch (t: Throwable) {
WiseTrackFactory.getLogger().error(
"Callable error [${t.message}] of type [${t.javaClass.canonicalName}]"
)
return@Callable null
}
}, millisecondDelay, TimeUnit.MILLISECONDS)
}
override fun teardown() {
scheduledThreadPoolExecutor!!.shutdownNow()
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy