io.axoniq.flowcontrol.producer.grpc.shutdown.TimeBasedShutDownPolicy Maven / Gradle / Ivy
/*
* Copyright (c) 2021. AxonIQ
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.axoniq.flowcontrol.producer.grpc.shutdown;
import io.axoniq.flowcontrol.producer.grpc.ShutdownPolicy;
import java.time.Duration;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.function.Consumer;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
/**
* @author Sara Pellegrini
* @author Milan Savic
* @since 1.0
*/
public class TimeBasedShutDownPolicy implements ShutdownPolicy {
private final Duration duration;
private final ShutdownPolicy delegate;
private final ScheduledExecutorService executor;
public TimeBasedShutDownPolicy(Duration duration) {
this(duration, Executors.newSingleThreadScheduledExecutor());
}
public TimeBasedShutDownPolicy(Duration duration, ScheduledExecutorService executor) {
this(duration, new NeverShutdownPolicy<>(), executor);
}
public TimeBasedShutDownPolicy(Duration duration,
ShutdownPolicy delegate,
ScheduledExecutorService executor) {
this.duration = duration;
this.delegate = delegate;
this.executor = executor;
}
@Override
public void initialize(Runnable shutdown, Consumer onError) {
this.delegate.initialize(shutdown, onError);
this.executor.schedule(shutdown, duration.toMillis(), MILLISECONDS);
}
@Override
public void onMessageConsumed(OUT message) {
delegate.onMessageConsumed(message);
}
@Override
public void onPublisherError(Throwable t) {
delegate.onPublisherError(t);
}
@Override
public void onPublisherComplete() {
delegate.onPublisherComplete();
}
@Override
public void shutdown() {
executor.shutdown();
delegate.shutdown();
}
}