如何在一定时间后不断增加值?

jfewjypa  于 2021-07-14  发布在  Java
关注(0)|答案(1)|浏览(300)

我想知道怎样每10秒增加一个变量+20,有什么简单的方法吗?

yzxexxkh

yzxexxkh1#

我可以这样做。

import java.time.LocalTime
import java.time.temporal.ChronoUnit.SECONDS

class Clocker(initial :Long, increment :Long, interval :Long) {
  private val start = LocalTime.now()
  def get :Long =
    initial + SECONDS.between(start, LocalTime.now()) / interval * increment
}

用法:

// start from 7, increase by 20 every 10 seconds
val clkr = new Clocker(7, 20, 10)

clkr.get  //res0: Long = 7

// 11 seconds later
clkr.get  //res1: Long = 27

// 19 seconds later
clkr.get  //res2: Long = 27

// 34 seconds later
clkr.get  //res3: Long = 67

相关问题