How would I constantly increase a value after a certain amount of time?

时间:2019-02-24 03:15:38

标签: scala time increment

I'm trying to figure out how to increase a variable by + 20 every 10 seconds, any simple way to do this?

1 个答案:

答案 0 :(得分:1)

这就是我可能会做的方式。

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