ProgressiveTask.java 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package com.serotonin.cdc.util;
  2. /**
  3. * @author Matthew Lohbihler
  4. */
  5. abstract public class ProgressiveTask implements Runnable {
  6. private boolean cancelled = false;
  7. protected boolean completed = false;
  8. private ProgressiveTaskListener listener;
  9. public ProgressiveTask() {
  10. // no op
  11. }
  12. public ProgressiveTask(ProgressiveTaskListener l) {
  13. listener = l;
  14. }
  15. public void cancel() {
  16. cancelled = true;
  17. }
  18. public boolean isCancelled() {
  19. return cancelled;
  20. }
  21. public boolean isCompleted() {
  22. return completed;
  23. }
  24. public final void run() {
  25. while (true) {
  26. if (isCancelled()) {
  27. declareFinished(true);
  28. break;
  29. }
  30. runImpl();
  31. if (isCompleted()) {
  32. declareFinished(false);
  33. break;
  34. }
  35. }
  36. completed = true;
  37. }
  38. protected void declareProgress(float progress) {
  39. ProgressiveTaskListener l = listener;
  40. if (l != null)
  41. l.progressUpdate(progress);
  42. }
  43. private void declareFinished(boolean cancelled) {
  44. ProgressiveTaskListener l = listener;
  45. if (l != null) {
  46. if (cancelled)
  47. l.taskCancelled();
  48. else
  49. l.taskCompleted();
  50. }
  51. }
  52. /**
  53. * Implementers of this method MUST return from it occasionally so that the cancelled status can be checked. Each
  54. * return must leave the class and thread state with the expectation that runImpl will not be called again, while
  55. * acknowledging the possibility that it will.
  56. *
  57. * Implementations SHOULD call the declareProgress method with each runImpl execution such that the listener can be
  58. * notified.
  59. *
  60. * Implementations MUST set the completed field to true when the task is finished.
  61. */
  62. abstract protected void runImpl();
  63. }