001/*
002 * (C) Copyright 2006-2017 Nuxeo (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package org.nuxeo.ecm.core.redis.retry;
017
018import java.util.concurrent.TimeUnit;
019
020import org.apache.commons.lang3.builder.ToStringBuilder;
021import org.apache.commons.logging.LogFactory;
022
023public class SimpleDelay implements Retry.Policy {
024
025    protected final int base;
026
027    protected final long delay;
028
029    protected int elapsed;
030
031    public SimpleDelay(int base, int delay) {
032        this.base = base;
033        this.delay = TimeUnit.MILLISECONDS.convert(delay, TimeUnit.SECONDS);
034    }
035
036    @Override
037    public boolean allow() {
038        return elapsed < delay;
039    }
040
041    @Override
042    public void pause() {
043        long computed = computeDelay();
044        LogFactory.getLog(SimpleDelay.class).warn("pausing for " + computed + " ms");
045        try {
046            Thread.sleep(computed);
047        } catch (InterruptedException e) {
048            Thread.currentThread().interrupt();
049        }
050        elapsed += computed;
051    }
052
053    protected long computeDelay() {
054        return base;
055    }
056
057    @Override
058    public String toString() {
059        return ToStringBuilder.reflectionToString(this);
060    }
061
062}