001    import java.util.concurrent.Delayed;
002    import java.util.concurrent.TimeUnit;
003    
004    /**
005     * DelayedTask - Lets you add a task to a j.u.concurrent.DelayQueue
006     * 
007     * @author Zeerix
008     */
009    public class DelayedTask implements Runnable, Delayed {
010    
011        private final Runnable task;
012        private final long endOfDelay;
013    
014        /**
015         * Wraps a Runnable task so you can put it into a DelayQueue
016         * 
017         * @param task the task that needs to be run after the delay
018         * @param delayMillis the delay in milliseconds
019         */
020        DelayedTask(Runnable task, long delayMillis) {
021            this.task = task;
022            this.endOfDelay = System.currentTimeMillis() + delayMillis;
023        }
024    
025        /**
026         * Runs the embedded task
027         */
028        @Override
029        public void run() {
030            task.run();
031        }
032    
033        /**
034         * Returns how long this task needs to be delayed
035         * 
036         * @param unit the TimeUnit of the result
037         */
038        @Override
039        public long getDelay(TimeUnit unit) {
040            return unit.convert(endOfDelay - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
041        }
042    
043        /**
044         * Compares order of two DelayedTasks
045         * 
046         * @param delayed the other object to compare to
047         */
048        @Override
049        public int compareTo(Delayed delayed) {
050            DelayedTask other = (DelayedTask) delayed;
051            if (this.endOfDelay < other.endOfDelay)
052                return -1;
053            else if (this.endOfDelay > other.endOfDelay)
054                return 1;
055            return 0;
056        }
057    }