jahilldev
jahilldev

Reputation: 3812

Scala Lift - Run system command and wait for completion

I'm currently using a class found here:

http://www.qualitybrain.com/?p=84

All is working well, however I need the code to wait for the command to finish and then return a true/false type response so I can then continue with the the result.

I'm using it in conjunction with OpenOffice to convert some documents, so waiting for the document conversion to finish before using the resulting files is essential.

Thanks for any help, much appreciated :)

Upvotes: 1

Views: 450

Answers (1)

nonVirtualThunk
nonVirtualThunk

Reputation: 2852

  1. The code should already wait for the command to finish, since receiveWithin is a blocking method. You can test this yourself simply by running the example main function with sleep 10 and a println before and after.
  2. Getting a boolean result from the run function should be pretty straightforward, you'll just have to make a small modification to the run function.

New run function:

def run(command:String) : Boolean = {
    println("gonna runa a command: " + Thread.currentThread)
    val args = command.split(" ")
    val processBuilder = new ProcessBuilder(args: _* )
    processBuilder.redirectErrorStream(true)
    val proc = processBuilder.start()

    //Send the proc to the actor, to extract the console output.
    reader ! proc

    //Receive the console output from the actor.
    //+========== Begin Modified Section ==============+
    //Here, we'll store the result instead of printing it, storing a None
    //if there was a timeout

    var commandResult : Option[String] = None
    receiveWithin(WAIT_TIME) {
        case TIMEOUT => commandResult = None
        case result:String => commandResult = Some(result)
    }

    //Here we interpret the result to return our boolean value
    commandResult match {
        case None => false
        case Some(s) => //... You'll have to transform the result to a true/false
            //however is most applicable to your use case
    }
}

Upvotes: 1

Related Questions