All Downloads are FREE. Search and download functionalities are using the official Maven repository.

base.task.RegularTaskHandler Maven / Gradle / Ivy

/**
 * Creative commons Attribution-NonCommercial license.
 *
 * http://creativecommons.org/licenses/by-nc/2.5/au/deed.en_GB
 *
 * NO WARRANTY IS GIVEN OR IMPLIED, USE AT YOUR OWN RISK.
 */
package base.task;

/**
 * Provides a mechanism to run a task at a regular interval without having
 * to play with threads. When implementing a RegularTask you must
 * ensure that the InterruptedException is respected to ensure the
 * application server shutdown process is not broken.
 */
public class RegularTaskHandler extends TaskHandler {

	private int interval = 1;

	/**
	 * Initialise a regular task.
	 *
	 * @param taskName
	 * @param interval
	 */
	public RegularTaskHandler(String taskName, Task task, int interval) {
		super(taskName, task);
		this.interval = interval;
	}

	/**
	 * Entry point to the handler. All work done by the handler is done within
	 * a loop, this allows tomcat to send a message to terminate the running
	 * of the thread. All work in the loop has a global Exception handler to
	 * prevent the thread terminating early.
	 */
	public void run() {

		try {
			task.run();
		} catch(InterruptedException ex) {}

		while(!finished) {
			try {
				sleep(interval * 1000);
				task.run();
			} catch(InterruptedException e) {
			} catch(Exception e) {
				e.printStackTrace();
				try { sleep(3 * 1000); } catch (InterruptedException ex) {}
			}
		}

	}

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy