package io.xunyss.commons.exec.support;

import io.xunyss.commons.exec.Watchdog;

/**
 *
 * @author XUNYSS
 */
public class TimeoutWatchdog extends Watchdog {
	
	private long timeout;
	private long startTime;
	private boolean isWatching;
	
	private final Object thisWatchdog;
	
	
	public TimeoutWatchdog(long timeout) {
		this.timeout = timeout;
		this.isWatching = true;
		this.thisWatchdog = this;
	}
	
	@Override
	protected void start() {
		startTime = System.currentTimeMillis();
		
		new Thread("Timeout-Watchdog") {
			@Override
			public void run() {
				long timeLeft;
				boolean isWaiting;
				
				synchronized (thisWatchdog) {
					timeLeft = timeout - (System.currentTimeMillis() - startTime);
					isWaiting = timeLeft > 0;
					
					while (isWatching && isWaiting) {
						try {
							// waiting for timeout
							thisWatchdog.wait(timeLeft);
						}
						catch (InterruptedException ex) {
							// ignore exception
						}
						timeLeft = timeout - (System.currentTimeMillis() - startTime);
						isWaiting = timeLeft > 0;
					}
				}
				
				if (!isWaiting) {
					// fire timeout
					onTimeout();
				}
			}
		}.start();
	}
	
	@Override
	protected void stop() {
		synchronized (thisWatchdog) {
			isWatching = false;
			thisWatchdog.notifyAll();
		}
	}
	
	public void cancel() {
		stop();
	}
	
	public void onTimeout() {
		// destroy Process
		destroyProcess();
	}
}

@@ -282,16 +282,37 @@
 atchdog;
+%09// FIXME: %EC%96%98%EB%A5%BC %EC%99%9C %EB%A7%8C%EB%93%A4%EC%97%88%EC%A7%80?
 %0D%0A%09%0D%0A%09%0D%0A

add fixme tag