001/**
002 *
003 * Copyright 2018 Florian Schmaus
004 *
005 * Licensed under the Apache License, Version 2.0 (the "License");
006 * you may not use this file except in compliance with the License.
007 * You may obtain a copy of the License at
008 *
009 *     http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.jivesoftware.smack;
018
019import java.util.Date;
020import java.util.concurrent.Delayed;
021import java.util.concurrent.TimeUnit;
022
023import org.jivesoftware.smack.util.Async;
024
025public class ScheduledAction implements Delayed {
026
027    enum Kind {
028        NonBlocking,
029        Blocking,
030    }
031
032    private final Runnable action;
033    final Date releaseTime;
034    final SmackReactor smackReactor;
035    final Kind kind;
036
037    ScheduledAction(Runnable action, Date releaseTime, SmackReactor smackReactor, Kind kind) {
038        this.action = action;
039        this.releaseTime = releaseTime;
040        this.smackReactor = smackReactor;
041        this.kind = kind;
042    }
043
044    /**
045     * Cancels this scheduled action.
046     *
047     * @return <code>true</code> if the scheduled action was still pending and got removed, <code>false</code> otherwise.
048     */
049    public boolean cancel() {
050        return smackReactor.cancel(this);
051    }
052
053    public boolean isDue() {
054        Date now = new Date();
055        return now.after(releaseTime);
056    }
057
058    public long getTimeToDueMillis() {
059        long now = System.currentTimeMillis();
060        return releaseTime.getTime() - now;
061    }
062
063    @Override
064    public int compareTo(Delayed otherDelayed) {
065        if (this == otherDelayed) {
066            return 0;
067        }
068
069        long thisDelay = getDelay(TimeUnit.MILLISECONDS);
070        long otherDelay = otherDelayed.getDelay(TimeUnit.MILLISECONDS);
071
072        return Long.compare(thisDelay, otherDelay);
073    }
074
075    @Override
076    public long getDelay(TimeUnit unit) {
077        long delayInMillis = getTimeToDueMillis();
078        return unit.convert(delayInMillis, TimeUnit.MILLISECONDS);
079    }
080
081    void run() {
082        switch (kind) {
083        case NonBlocking:
084            action.run();
085            break;
086        case Blocking:
087            Async.go(() -> action.run());
088            break;
089        }
090    }
091}