https://kotlinlang.org logo
#server
Title
# server
a

Ans Trakhtman

02/27/2024, 1:52 PM
I’m stuck on making an actor in Akka and have it scheduled to run every X seconds:
Copy code
import akka.actor.*
import com.typesafe.config.Config
import kotlin.time.Duration.Companion.seconds


class JobsScheduler {
    fun run(config: Config) {
        val system = ActorSystem.create("jobsScheduler", config)
        val job = system.actorOf(Job.props(), "job1")
        system.scheduler.scheduleOnce(5.seconds, job, Job.Message("foo"));  // this needs some ExecutorContext, which I can't figure out what it is. 
    }
}
I would greatly appreciate any help to make this dummy example run. Can’t figure out what’s wrong 🤦
I got it down to job not being runnable
Finally got it to work:
Copy code
class JobsScheduler {
    fun run(config: Config) {
        val system = ActorSystem.create("jobsScheduler", config)
        val job = system.actorOf(Props.create(Job::class.java), "job")

        val anonymousFunction = fun() {
            job.tell("hello", ActorRef.noSender());
        }

        system.scheduler().scheduleWithFixedDelay(Duration.ofSeconds(0), Duration.ofSeconds(5), anonymousFunction, system.dispatcher())
    }
}
Not clear why I had to wrap it in a function
t

Ties

02/27/2024, 3:21 PM
I dont know Akka, so it is just a guess. But by wrapping it into a function you do make it lazy (as in, you create a function that needs to be executed before the code will run), instead of the code being immediately being evaluated. Lazy evaluation is generally what you need if you want the code to be executed asynchronously
6 Views