Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Background task in Scala

I have a cache I want to periodically check and prune. In Java, I'd do the following:

new Thread(new Runnable() {   void run() {     while (true) {        Thread.sleep(1000);       // clear the cache's old entries     }   } }).start(); 

Sure, I'd have some issues with thread-safe types to use as the cache, but putting that aside, my question is simple. What's the Scala way of running a recurring background task -- something you don't want running in the application's main thread?

I've used actors a bit and I guess my problem in this scenario is that I don't have anything to generate a message that it's time to clear the cache. Or rather, the only way I can imagine to generate those messages is to create a thread to do it...

EDIT: I need people to vote on answers -- they all look good to me

like image 503
Jeb Avatar asked Jun 13 '11 18:06

Jeb


1 Answers

There are many ways to do that, but I would do something simple like the following.

import scala.concurrent.ops._  spawn {   while (true) {      Thread.sleep(1000);     // clear the cache's old entries   } } 

Hope this helps.

like image 131
k4200 Avatar answered Sep 19 '22 18:09

k4200