skip to Main Content

My Goal
is to be able to launch a daily task at a certain time every day and, if necessary, also be able to stop it, and if the previous day’s task is still active on the following day, I delete it

What am I trying to do

  1. Method that takes a task, a daily time and a boolean that indicates whether to start immediately or wait for the next time given in input (either today’s or tomorrow’s) to start the task every 24 hours
  2. Method to interrupt this daily task repetition

Code suggested by artificial intelligence

var executor: ScheduledExecutorService? = null
var scheduledFuture: ScheduledFuture<*>? = null
val firstExecution = AtomicBoolean(true)

fun startTaskAt(hour: Int, task: Runnable, immediate: Boolean = false) {
    executor = Executors.newSingleThreadScheduledExecutor()
    // get current date
    val now = LocalDateTime.now()

    // creates a new LocalDateTime instance with the fixed time
    val scheduledTime = LocalDateTime.of(now.year, now.month, now.dayOfMonth, hour, 0, 0, 0)

    // if the set time has already passed today, add a day to the date
    if (scheduledTime.isBefore(now)) {
        scheduledTime.plusDays(1)
    }

    //I calculate the initial delay is respect if it's the first time I launch it
    val initialDelay = if (firstExecution.getAndSet(false)) {
        //or if the input parameter tells me to start it immediately
        if (immediate) 0 else {
            val millisUntilScheduledTime = Duration.between(now, scheduledTime).toMillis()
            //if for some reason this value is negative I still set it to 0
            if (millisUntilScheduledTime < 0) 0 else millisUntilScheduledTime
        }
    } else {
        //I'm in case it's not the first time I've run it and therefore I don't have to add the initial delay to reach the set time
        0
    }
    //cancel the last task, if any
    scheduledFuture?.cancel(true)

    // start the new task after the initial delay, then every 24 hours
    scheduledFuture = executor?.scheduleWithFixedDelay(
        task,
        initialDelay,
        24 * 60 * 60 * 1000,
        TimeUnit.MILLISECONDS
    )
}

fun stopRepeatedDailyTask() {
    firstExecution.getAndSet(true)
    scheduledFuture?.cancel(true)
    scheduledFuture = null
    executor?.shutdownNow()
}

Is this code suggested to me by the AI correct?
Is there a better way to do what I need?


Please signup or login to give your own answer.
Back To Top
Search