0

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?

AccountForWorks
  • 91
  • 1
  • 10
  • By "native kotlin" do you mean literally `Kotlin/Native` or using Kotlin for a JVM app? What kind of app are you actually writing? It will impact how you can create such a long-running task. What should happen if the device is suspended at the time the task is supposed to run? Executors won't be available for `Kotlin/Native`. No one who has experience looking at code from ChatGPT is going to bother wasting time hunting for all the subtly wrong things it undoubtedly has put there in that code. If it was your own code, I wouldn't mind because someone would be learning something. – Tenfour04 Mar 07 '23 at 20:53
  • I still have to decide whether to put it inside a ktor server or to make a desktop app using jetbrain compose for desktop (both written in kotlin) – AccountForWorks Mar 08 '23 at 08:09
  • If I had to do it for android I would definitely have used the WorkerManager, but since I don't have to use it in android I wanted to understand what I could use and how. (I lost an afternoon of work asking ChatGpt about this and changing his answers from time to time) – AccountForWorks Mar 08 '23 at 08:19

0 Answers0