All Downloads are FREE. Search and download functionalities are using the official Maven repository.

main.wisp.task.RepeatedTaskManager.kt Maven / Gradle / Ivy

There is a newer version: 2024.09.17.200749-4708422
Show newest version
package wisp.task

import com.github.michaelbull.retry.RetryFailure
import com.github.michaelbull.retry.RetryInstruction
import com.github.michaelbull.retry.policy.binaryExponentialBackoff
import com.github.michaelbull.retry.policy.plus
import io.micrometer.core.instrument.MeterRegistry
import io.micrometer.core.instrument.Metrics
import wisp.task.exception.NoTaskFoundException
import wisp.task.exception.TaskAlreadyExistsException

/**
 * Basic management of repeated tasks.
 */
class RepeatedTaskManager @JvmOverloads constructor(
    private val meterRegistry: MeterRegistry = Metrics.globalRegistry
) {
    private val repeatedTasks = mutableMapOf()

    /**
     * Creates the repeated task with the details supplied.  If the repeated task already
     * exists, a [TaskAlreadyExistsException] is thrown.
     *
     * Does not start the task.
     */
    @JvmOverloads
    fun createTask(
        name: String,
        meterRegistry: MeterRegistry = this.meterRegistry,
        repeatedTaskConfig: RepeatedTaskConfig = RepeatedTaskConfig(),
        retryPolicy: suspend RetryFailure.() -> RetryInstruction =
            defaultThrowableRetryPolicy +
                    binaryExponentialBackoff(
                        base = repeatedTaskConfig.defaultJitterMs,
                        max = repeatedTaskConfig.defaultMaxDelayMs
                    ),
        taskConfig: TaskConfig = TaskConfig(),
        task: (name: String, taskConfig: TaskConfig) -> Status
    ): RepeatedTask {
        if (taskExists(name)) {
            throw TaskAlreadyExistsException(name)
        }

        val repeatedTask = RepeatedTask(
            name,
            meterRegistry,
            repeatedTaskConfig,
            retryPolicy,
            taskConfig,
            task
        )

        repeatedTasks[name] = repeatedTask
        return repeatedTask
    }

    fun getTask(taskName: String): RepeatedTask {
        return repeatedTasks[taskName] ?: throw NoTaskFoundException(taskName)
    }

    fun taskExists(taskName: String): Boolean {
        return repeatedTasks.containsKey(taskName)
    }

    /**
     * Returns true if a repeated task with the name supplied is running.
     * If the task does not exist or is not running, return false.
     */
    fun isTaskRunning(taskName: String): Boolean {
        return repeatedTasks[taskName]?.isRunning() ?: false
    }

    fun shutDown() {
        repeatedTasks.values.forEach { it.shutDown() }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy