-4

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

  • Possible duplicate of [Run a function periodically in Scala](https://stackoverflow.com/questions/25351186/run-a-function-periodically-in-scala) – Brian McCutchon Feb 24 '19 at 06:15

1 Answers1

1

This is how I might do it.

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
}

usage:

// 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
jwvh
  • 50,871
  • 7
  • 38
  • 64