Return to Snippet

Revision: 63066
at April 5, 2013 07:29 by laurenceosx


Updated Code
def threadedPrintStringBuffer( StringBuffer aStringBuffer, Boolean aStop = false ) {
	// useful for real-time printing of process output
	/*
		Example use:
			def pb      = new ProcessBuilder( 'cmd', '/c', 'dir' );
			def process = pb.start();
			def sb1     = new StringBuffer();
			process.consumeProcessOutput( sb1, sb1 );
			def stop = threadedPrintStringBuffer( sb1 );
			process.waitFor();
			stop = true;
	*/
	Thread.start {
		int sbOldSize = 0;
		int sbNewSize = 0;
		def nap    = { itNapTime = 100 -> Thread.sleep(itNapTime); } ;
		int sz, delta;
		def somethingToDo = {
			sz    = aStringBuffer.length();
			delta = sz - sbOldSize;
			(delta > 0); // return		
		} ;
		def doWork = {	
			sbNewSize = sz;
			System.out.print( aStringBuffer.substring( sbOldSize, sbNewSize-1 ) );
			System.out.flush(); // very important !!!
			sbOldSize = sbNewSize;
		} ;
		
		while(true) {
			if ( somethingToDo() ) { doWork(); }
			nap();
			if ( aStop && !somethingToDo() ) { break; }
		} // end while	
	} // end Thread
	return aStop; // !!!
}

Revision: 63065
at April 5, 2013 06:26 by laurenceosx


Initial Code
def threadedPrintStringBuffer( StringBuffer aStringBuffer, Boolean aStop = false ) {
	// useful for real-time printing of process output
	/*
		Example use:
			def pb      = new ProcessBuilder( 'cmd', '/c', 'dir' );
			def process = pb.start();
			def sb1     = new StringBuffer();
			process.waitForProcessOutput( sb1, sb1 );
			def stop = threadedPrintStringBuffer( sb1 );
			process.waitFor();
			stop = true;
	*/
	Thread.start {
		int sbOldSize = 0;
		int sbNewSize = 0; 
		while(true) {
			int sz    = aStringBuffer.length();
			int delta = sz - sbOldSize; 
			if ( delta > 0 ) {		
				sbNewSize = sz;
				System.out.print( aStringBuffer.substring( sbOldSize, sbNewSize-1 ) );
				System.out.flush(); // very important !!!
				sbOldSize = sbNewSize;
			}
			if (aStop) { break; } // !!!
			Thread.sleep(100);
		} // end while	
	}
	return aStop; // !!!
}

Initial URL

                                

Initial Description
None

Initial Title
Groovy - threadedPrintStringBuffer

Initial Tags
groovy

Initial Language
Groovy