001/**
002 *
003 * Copyright 2018-2024 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    @SuppressWarnings("JavaUtilDate")
054    public boolean isDue() {
055        Date now = new Date();
056        return now.after(releaseTime);
057    }
058
059    @SuppressWarnings("JavaUtilDate")
060    public long getTimeToDueMillis() {
061        long now = System.currentTimeMillis();
062        return releaseTime.getTime() - now;
063    }
064
065    @Override
066    public int compareTo(Delayed otherDelayed) {
067        if (this == otherDelayed) {
068            return 0;
069        }
070
071        long thisDelay = getDelay(TimeUnit.MILLISECONDS);
072        long otherDelay = otherDelayed.getDelay(TimeUnit.MILLISECONDS);
073
074        return Long.compare(thisDelay, otherDelay);
075    }
076
077    @Override
078    public long getDelay(TimeUnit unit) {
079        long delayInMillis = getTimeToDueMillis();
080        return unit.convert(delayInMillis, TimeUnit.MILLISECONDS);
081    }
082
083    void run() {
084        switch (kind) {
085        case NonBlocking:
086            action.run();
087            break;
088        case Blocking:
089            Async.go(() -> action.run());
090            break;
091        }
092    }
093}