Computation with time limit

后端 未结 9 2296
你的背包
你的背包 2021-01-02 12:08

I\'m trying to write a construct which allows me to run computations in a given time window. Something like:

def expensiveComputation(): Double = //... some          


        
相关标签:
9条回答
  • 2021-01-02 12:58

    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".

    0 讨论(0)
  • 2021-01-02 13:06

    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.

    0 讨论(0)
  • 2021-01-02 13:13

    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.

    0 讨论(0)
提交回复
热议问题