简体   繁体   中英

Step function lambda that executes different tasks generically and on different intervals

So I am writing a Lambda that is part of a step function, this lambda is getting a map of task name and on what interval to execute it, for example -("task1",5) --> task1 will be executed every 5 minutes. This lambda function is within a loop condition in the step machine and could potentially be looping for 24 hours. Upon each iteration of the step function loop, it waits for 5 minutes. This means that 5 minutes is my execution iteration. In such case we understand that "task1" should actually be executed on every iteration. In my below example I also have ("task2",60) - this task should be executed every 12 iterations. My Lambda code at the moment looks like:

protected Map<String, Object> customHandleLambdaRequest(Map<String, Object> inputMap, Context context) throws Exception {

    Map<String, Object> tasks = (Map<String, Object>) inputMap.get("tasks");
    if (tasks.isEmpty()) {
        return inputMap;
    }

    int tick = (int) inputMap.get("tick");
    tick = tick + 5;
    inputMap.put("tick", tick);

    if (tasks.containsKey("task1") || isEvenlyDividable((int) tasks.get("task1"),tick)) {
        //do something
    }

    if (tasks.containsKey("task2") || isEvenlyDividable((int) tasks.get("task2"),tick)) {
        //do something
    }

    return inputMap;
}

The thing is, I keep on adding many tasks and end up having a code that looks like one big "if" (ugly). My question for the stack overflow code wizards are:

  1. how can I make this code more generic and not have all these if conditions?
  2. I would like to adhere to my interval time accurately and executing all the tasks might take a few seconds which in turn will cause my next iteration to be a few seconds late, would you suggest that I sample the first iteration time and keep that as my five minutes compass?

Make additional lambdas.

I know that sounds contrite, but it is the best practice accepted behavior.

Each lambda should be a self contained task only called when needed. If you have a lot of different scenarios, then make additional lambdas and put a choice Task in your State Machine to determine which lambda to call.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM