package eu.simstadt.nf4j.async; import eu.simstadt.nf4j.FailedTransmissionException; /** * This task frequently polls the status of an asynchronous job within a separate poll thread. Changes of the * jobs status will be signaled to all of the job status listeners registered at the job. * You can cancel this task by calling job.cancel(). * * @author Marcel Bruse */ public class PollJobStatusTask implements Runnable { /** The job for which you want to poll status changes for. */ private AsyncJob job; /** * Don't flood your nF server with status request. This interval ensures that your server will receive * a status request within every time interval. */ private int interval; /** * Constructor with asynchronous job and the poll interval. * * @param job The job to update frequently. * @param interval The time interval for one request. */ public PollJobStatusTask(AsyncJob job, int interval) { this.job = job; this.interval = interval; } /** * This method performs the poll operation asynchronously in the jobs separate poll thread. * Job status listeners will be notified upon status changes. */ @Override public void run() { try { while (!job.hasFinished() && !job.hasFailed() && job.keepPolling()) { job.triggerStatusUpdate(); Thread.sleep(interval * 1000l); } // At this line the job may have finished or failed before the job listeners could be notified. // Therefore, we have to ensure that all listeners know the current status. job.notifyJobStatusListeners(); } catch (FailedTransmissionException ex) { job.cancel(); } catch (InterruptedException ex) { // Canceled by the main thread } } }