ScheduledAction.java

  1. /**
  2.  *
  3.  * Copyright 2018 Florian Schmaus
  4.  *
  5.  * Licensed under the Apache License, Version 2.0 (the "License");
  6.  * you may not use this file except in compliance with the License.
  7.  * You may obtain a copy of the License at
  8.  *
  9.  *     http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.jivesoftware.smack;

  18. import java.util.Date;
  19. import java.util.concurrent.Delayed;
  20. import java.util.concurrent.TimeUnit;

  21. import org.jivesoftware.smack.util.Async;

  22. public class ScheduledAction implements Delayed {

  23.     enum Kind {
  24.         NonBlocking,
  25.         Blocking,
  26.     }

  27.     private final Runnable action;
  28.     final Date releaseTime;
  29.     final SmackReactor smackReactor;
  30.     final Kind kind;

  31.     ScheduledAction(Runnable action, Date releaseTime, SmackReactor smackReactor, Kind kind) {
  32.         this.action = action;
  33.         this.releaseTime = releaseTime;
  34.         this.smackReactor = smackReactor;
  35.         this.kind = kind;
  36.     }

  37.     /**
  38.      * Cancels this scheduled action.
  39.      *
  40.      * @return <code>true</code> if the scheduled action was still pending and got removed, <code>false</code> otherwise.
  41.      */
  42.     public boolean cancel() {
  43.         return smackReactor.cancel(this);
  44.     }

  45.     public boolean isDue() {
  46.         Date now = new Date();
  47.         return now.after(releaseTime);
  48.     }

  49.     public long getTimeToDueMillis() {
  50.         long now = System.currentTimeMillis();
  51.         return releaseTime.getTime() - now;
  52.     }

  53.     @Override
  54.     public int compareTo(Delayed otherDelayed) {
  55.         if (this == otherDelayed) {
  56.             return 0;
  57.         }

  58.         long thisDelay = getDelay(TimeUnit.MILLISECONDS);
  59.         long otherDelay = otherDelayed.getDelay(TimeUnit.MILLISECONDS);

  60.         return Long.compare(thisDelay, otherDelay);
  61.     }

  62.     @Override
  63.     public long getDelay(TimeUnit unit) {
  64.         long delayInMillis = getTimeToDueMillis();
  65.         return unit.convert(delayInMillis, TimeUnit.MILLISECONDS);
  66.     }

  67.     void run() {
  68.         switch (kind) {
  69.         case NonBlocking:
  70.             action.run();
  71.             break;
  72.         case Blocking:
  73.             Async.go(() -> action.run());
  74.             break;
  75.         }
  76.     }
  77. }