PollJobStatusTask.java 1.71 KB
Newer Older
bruse's avatar
bruse committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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.
	 */
21
	private int interval;
bruse's avatar
bruse committed
22
23
24
25
26
27
28

	/**
	 * Constructor with asynchronous job and the poll interval.
	 * 
	 * @param job The job to update frequently.
	 * @param interval The time interval for one request.
	 */
29
	public PollJobStatusTask(AsyncJob job, int interval) {
bruse's avatar
bruse committed
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
		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
		}
	}
	
}