Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Hour, minutes & sec in delay kotlin

I want to use delay in my launch function. I always use xxxL value for delay. Is there any function to convert seconds, minutes & hours . For example

For 30 second

delay(30)

For 1 minute

delay(1)

For 2 Hour

delay(2)

It's so much confusing to multiple by value. Thanks

I tried from Delay with Duration, but I am getting error in here

delay(Duration(1.minutes))

imports

import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlin.time.Duration
import kotlin.time.Duration.Companion.minutes

Error

enter image description here

I don't know what I am doing wrong in here.

UPDATE

which one should I use to import?

enter image description here

like image 489
Vivek Modi Avatar asked Dec 12 '25 11:12

Vivek Modi


2 Answers

You can also use delay(1.minutes).

Required import: kotlin.time.Duration.Companion.minutes

like image 189
Thracian Avatar answered Dec 15 '25 00:12

Thracian


The delay() function can take a Long value when you wants to delay by a certain amount of milliseconds or any Duration.

Kotlin provides helpers to create duration given any number. You can create them with special extension properties from the Duration object.

To create duration :

val second: Duration = 1.seconds
val duration: Duration = 2.4.minutes

You can use the delay function with it

scope.launch {
    delay(seconds)
    delay(duration)
}

A duration can be converted back to milliseconds in Long with:

val oneSecondInMillis: Long = seconds.inWholeMilliseconds
like image 38
Lionel Briand Avatar answered Dec 15 '25 00:12

Lionel Briand



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!