I\'m trying to write a construct which allows me to run computations in a given time window. Something like:
def expensiveComputation(): Double = //... some
To the best of my knowledge, either you yield (the computation calls to some scheduler) or you use a thread, which gets manipulated from the "outside".
If you are ok for the code of expensiveComputation
to check Thread.interrupted()
frequently, pretty easy. But I suppose you are not.
I don't think there is any solution that will work for arbitrary expensiveComputation
code.
The question is what are you prepared to have as constraint on expensiveComputation.
You have the deprecated and quite unsafe Thead.stop(Throwable)
too. If your code does not modify any object but those it created by itself, it might work.
I saw a pattern like this work well for time-limited tasks (Java code):
try {
setTimeout(45*60*1000); // 45 min in ms
while (not done) {
checkTimeout();
// do some stuff
// if the stuff can take long, again:
checkTimeout();
// do some more stuff
}
return Some(result);
}
catch (TimeoutException ex) {
return None;
}
The checkTimeout()
function is cheap to call; you add it to code so that it is called reasonably often, but not too often. All it does is check current time against timer value set by setTimeout()
plus the timeout value. If current time exceeds that value, checkTimeout()
raises a TimeoutException
.
I hope this logic can be reproduced in Scala, too.