Call a function periodically in a distributed multiple containers/processes environment?

Viewed 61

I just took over a project and one of the functional requirements is to call a function every 10 minutes. I found the following code

async Task Run(CancellationToken cancel)
{
    while (!cancel.IsCancellationRequested)
    {
        await DoSomething(cancel);
        await Task.Delay(TimeSpan.FromMinutes(10), cancel);
    }
}

However, I found the application is deployed to Kubernetes with multiple instances (replicaCount > 1). The logs show the function is called twice every 10 minutes when replicaCount == 2.

How to make sure the function is called once by multiple containers?

1 Answers

You can use external service like Redis. so when doing task call Redis and set last calling time.

async Task Run(CancellationToken cancel)
{
    // abstraction view of redis connection
    var cache = RedisConnectorHelper.Connection.GetDatabase();  

    while (!cancel.IsCancellationRequested)
    {
        await DoSomething(cancel);
        // Program.REDISDOYINGKEY specific key
        cache.StringSet(Program.REDISDOYINGKEY, DateTime.Now); 
        await Task.Delay(TimeSpan.FromMinutes(10), cancel);
    }
}

you can see this post for refdis link1

Related