iknow
iknow

Reputation: 9862

Execute function every full minute android/kotlin

Is this possible to execute function in android every minute starting from full minute, so eg. when I run my app at 8:30:12 the first function call will be at 8:31:00 and next at 8:32:00 and so on.

Upvotes: 3

Views: 2021

Answers (2)

Animesh Sahu
Animesh Sahu

Reputation: 8096

You have to first calculate the time required to become exact minute that is starting the task at 8:30:12, first call should happen at 8:31:00.

So for that you can pull current time using System.currentTimeMillis() and then ceil it's minute value to the nearest integer,

// import kotlin.math.ceil
val firstCallTime = ceil(System.currentTimeMillis() / 60_000.0).toLong() * 60_000

Then you can use coroutines to handle your task that will use a CommonPool to get reusable threads from and won't require to you to create threads.

// scope can be anything, for instance you want to call the function
// only when client is using your application then use viewModelScope provided,
// otherwise your own scope like `val scope = CoroutineScope(Dispatchers.Main)`
// Or use Dispatchers.Default for CPU intensive tasks

val parentJob = scope.launch {
    // suspend till first minute comes after some seconds
    delay(firstCallTime - System.currentTimeMillis())
    while (true) {
        launch {
            yourFunctionToBeCalled()
        }
        delay(60_000)  // 1 minute delay (suspending)
    }
}

// If you ever want your job to cancel just do a cancel,
// the function delay suspends and so cancellable without interrupting the threads
// parentJob.cancel()

Upvotes: 2

Tirth Mehta
Tirth Mehta

Reputation: 329

Use PeriodicWorkRequest along with WorkManager class in android. It goes like this:

    val work = PeriodicWorkRequestBuilder<MyWorker>(60, TimeUnit.SECONDS)
.build();
    val workManager = WorkManager.getInstance(context);
    workManager.enqueuePeriodicWork(work);

Upvotes: 0

Related Questions