import java.util.Date;
import java.util.GregorianCalendar;


/**
 * The source code for the Eater jar which is used with the Puller to impose
 * a certain availability on the servers used
 * 
 * @author Majd Kokaly
 *
 */
public class Eater {

/**
 * The main class which is run when the jar is executed
 * 
 * @param args[0] The percentage of the CPU to eat. (ex. 0.5 means that 50% of the idle cpu usage will be eaten)
 * @param args[1] The length of time in milliseconds that the eater will run
 */
public static void main (String[] args) {
		
		double percentage = Double.parseDouble(args[0]);
		double forHowLong = Double.parseDouble(args[1]);
		
		long cycleTime = 100;
		if (percentage >= 1) {
			percentage = 0.99;
		}
		int busyTime = (int) (percentage * cycleTime);
		
		GregorianCalendar now = new GregorianCalendar();
		GregorianCalendar timeToStop = new GregorianCalendar();
		GregorianCalendar timeToExitLoop = new GregorianCalendar();
		timeToExitLoop.add(GregorianCalendar.SECOND, (int) Math.round( (forHowLong - Math.floor(forHowLong) )*60  ) );
		timeToExitLoop.add(GregorianCalendar.MINUTE, (int) forHowLong);
		
		while (now.before(timeToExitLoop)) {
			try {
				Thread.sleep(cycleTime - busyTime);
			} catch (InterruptedException e) {
			
			}
			now.setTime(new Date());
			timeToStop.setTime( new Date() );
			timeToStop.add(GregorianCalendar.MILLISECOND, busyTime);
			
			while (now.before(timeToStop)) {
				now.setTime(new Date());
			}	
		}
}

}