How to call a function after delay in Kotlin?

前端 未结 11 1946
南笙
南笙 2020-11-30 19:07

As the title, is there any way to call a function after delay (1 second for example) in Kotlin?

11条回答
  •  悲哀的现实
    2020-11-30 19:37

    I recommended using SingleThread because you do not have to kill it after using. Also, "stop()" method is deprecated in Kotlin language.

    private fun mDoThisJob(){
    
        Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate({
            //TODO: You can write your periodical job here..!
    
        }, 1, 1, TimeUnit.SECONDS)
    }
    

    Moreover, you can use it for periodical job. It is very useful. If you would like to do job for each second, you can set because parameters of it:

    Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit);

    TimeUnit values are: NANOSECONDS, MICROSECONDS, MILLISECONDS, SECONDS, MINUTES, HOURS, DAYS.

    @canerkaseler

提交回复
热议问题