From 5230ed3515a10bb1dc085b0ac9d5730661c92792 Mon Sep 17 00:00:00 2001 From: Victor Toni Date: Sat, 20 Apr 2024 19:37:10 +0200 Subject: [PATCH] Add example for exponential backoff --- autopaho/examples/backoff/backoff.go | 51 ++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 autopaho/examples/backoff/backoff.go diff --git a/autopaho/examples/backoff/backoff.go b/autopaho/examples/backoff/backoff.go new file mode 100644 index 0000000..7c8d402 --- /dev/null +++ b/autopaho/examples/backoff/backoff.go @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2024 Contributors to the Eclipse Foundation + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v2.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * https://www.eclipse.org/legal/epl-2.0/ + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause + */ + +package main + +import ( + "fmt" + "math" + + "github.com/eclipse/paho.golang/autopaho" +) + +func main() { + // used to calculate the number of iterations + const interationBase = 1 + + backoffStrategy := autopaho.DefaultExponentialBackoffStrategy() + + backoff := backoffStrategy.Backoff() + + minBackoff := int64(math.MaxInt64) + maxBackoff := int64(0) + iterationsTotal := 0 + for i := 0; i < 22; i++ { + iterations := interationBase << i + for j := 0; j < iterations; j++ { + backoffTime := backoff.Next().Milliseconds() + if backoffTime < minBackoff { + minBackoff = backoffTime + } + if backoffTime > maxBackoff { + maxBackoff = backoffTime + } + } + iterationsTotal += iterations + + fmt.Printf("After % 8d iterations, min: %d, max: % 7d\n", iterationsTotal, minBackoff, maxBackoff) + } +}