Search code examples
javatimerrunnable

Run the method during prescribed number of minutes


There is a class Algorithm that has a method runAlgorithm. Currently it performs some predefined number of iterations, e.g. 100 iterations, after what it stops. This method is called from the class Test.

Now I need to update my code to be able to run the method runAlgorithm for a specified number of minutes, e.g. 5 minutes, after what it must be stopped.

As a result, I should be able to select the stopping criterion, i.e. time or number of iterations: algorithm.runAlgorithm('time',5) or algorithm.runAlgorithm('iterations',100).

I'm not sure how to do this. Should the class Algorithm be implemented as Runnable? Or do I need to create a timer in the class Test? A guidance will be highly appreciated.

public class Test {                                             

public static void main(String[] args) 
{

   init();

   Algorithm algorithm = new Algorithm();

   // 5 minutes is a stopping criterion for the algorithm
   Solution solution = algorithm.runAlgorithm('time',5);

   System.out.println(solution);

}

}

Solution

  • From the initial statement 100 iterations I assume runAlgorithm is basically a loop. Given that, you would just change the loop like so:

    public Solution runAlgorithm( String method, int duration )
        Solution solution = null;
        if ( method.equals( "time" ) {
            long start = System.currentTimeMillis();
            while ( true ) {
                if ( System.currentTimeMillis() - start > duration ) {
                    break;
                }
                // do stuff
            }
        }
        else {
            for ( int iter = 0; iter < 100; iter++ ) {
                // do stuff
            }
        }
        return solution;
    }