탐비의 개발 낙서장

[Kotlin] 코틀린 Timer 본문

프로그래밍/Kotlin

[Kotlin] 코틀린 Timer

탐비_ 2021. 8. 2. 23:49

 

 

Timer

 

Timer

 

 일정 주기마다 동작을 실행하기 위해 Timer를 사용할 수 있습니다. 원래 JAVA에서는 new TimerTask()를 통해 별도로 TimerTask 객체를 선언해주어야 했지만, 코틀린에서는 아래와 같이 편하게 사용할 수 있게 되었습니다.

 

import kotlin.concurrent.timer

fun run(){
	timer(period = 1000, initialDelay = 1000){ // 1초 후부터 1초 간격 실행
		// SomethingToDo..

		if (isStopCondition())
			cancel()
	}
}

 

 위 코드와 같이 kotlin.concurrent.timer를 import 한 후, 밀리세컨드 단위로 시간을 입력해 실행 타이머를 실행합니다. 만약 작업이 완료되어, 종료 조건에 도달했다면 cancel()을 통해 타이머 작업을 멈춥니다.

 

 코틀린 타이머의 구현체는 Timer.java의 schedule() 함수인데 해당 파일로 가면 다음과 같은 주석이 달려있습니다.

If an execution is delayed for any reason (such as garbage collection or other background activity), subsequent executions will be delayed as well.
In other words, it is appropriate for activities where it is more important to keep the frequency accurate in the short run than in the long run. This includes most animation tasks, such as blinking a cursor at regular intervals. 

 

 해석하면 가비지컬렉션이나 다른 백그라운드 작업으로 인해 실행이 지연되면 뒤에오는 실행도 지연되므로, 빈도를 정확하게 유지하는 것이 더 중요한 작업에 더 적합하다고 합니다.

 하지만 이렇게 지연되면 결국 정확히 원하는 주기만큼 실행하고 싶다는 목표에 맞지 않게됩니다.

 

 

 

fixedRateTimer

 

 대신 이러한 작업을 위해 작성되어 있는 함수가 별도로 있습니다. 이 함수도 역시 Timer.java에서 찾을수 있는데 scheduleAtFixedRate()라는 함수입니다. 아래는 해당 함수에 대한 주석입니다.

In fixed-rate execution, each execution is scheduled relative to the scheduled execution time of the initial execution. If an execution is delayed for any reason (such as garbage collection or other background activity), two or more executions will occur in rapid succession to "catch up." In the long run, the frequency of execution will be exactly the reciprocal of the specified period (assuming the system clock underlying Object.wait(long) is accurate).
Fixed-rate execution is appropriate for recurring activities that are sensitive to absolute time, such as ringing a chime every hour on the hour, or running scheduled maintenance every day at a particular time.

 

 이것도 해석해보면 각 실행이 초기 실행의 예약된 실행 시간에 비례하여 어떤 이유로든 실행이 지연되면 두 개 이상의 실행이 연속적으로 발생하여 "따라잡을" 수 있다고 되어있네요. 추가적으로 매 시간마다 차임벨을 울리거나 특정 시간에 유지 보수를 실행하는 것과 같이 절대 시간에 민감한 반복 작업에 적합하다고 되어있습니다.

 

 일반적으로 생각하는 타이머의 기능이 해당 함수에 담겨있는 것 같습니다. 코틀린에서의 사용법은 다음과 같습니다.

import kotlin.concurrent.timer

fun run(){
	fixedRateTimer(period = 1000, initialDelay = 1000){
		// SomethingToDo..

		if (isStopCondition())
			cancel()
	}
}

 

 

References

https://huiung.tistory.com/181

https://docs.oracle.com/javase/8/docs/api/java/util/Timer.html