Capped exponential backoff with jittered retry loop

C
#define _POSIX_C_SOURCE 200809L
#include <stdint.h>
#include <stdlib.h>
#include <time.h>
int retry_backoff(int (*task)(void *), void *ctx, int attempts, unsigned base_ms) {
    uint64_t delay = base_ms;
    for (int i = 0; i < attempts; i++) {
        if (task(ctx) == 0) return 0;
        if (i + 1 < attempts) {
            uint64_t cap = delay > 30000 ? 30000 : delay;
            uint64_t wait = cap + (uint64_t)rand() % (cap / 2 + 1);
            struct timespec ts = { (time_t)(wait / 1000), (long)(wait % 1000) * 1000000L };
            nanosleep(&ts, NULL);
            delay = cap * 2;
        }
    }
    return -1;
}