10

I am trying to implement Multithreading in AWS lambda. This is a Sample code that defines the format of my original code which I am trying to execute in lambda.

import threading
import time

def this_will_await(arg,arg2):
  print("Hello User")
  print(arg,arg2)

def this_should_start_then_wait():
  print("This starts")
  timer = threading.Timer(3.0, this_will_await,["b","a"])
  timer.start()
  print("This should execute")

this_should_start_then_wait()

In my local Machine, this code is working fine. The output I am receiving is:

This starts
This should execute
.
.
.
Hello User
('b', 'a')

Those 3 . represents that it waited for 3 seconds to complete the execution.

Now when I execute the same thing in AWS lambda. I am only receiving

This starts
This should execute

I think it's not calling the this_will_await() function.

1 Answer 1

14

Have you tried adding timer.join()? You'll need to join the Timer thread because otherwise the Lambda environment will kill off the thread when the parent thread finishes.

This code in a Lambda function:

import threading
import time

def this_will_await(arg,arg2):
  print("Hello User")
  print(arg,arg2)

def this_should_start_then_wait():
  print("This starts")
  timer = threading.Timer(3.0, this_will_await,["b","a"])
  timer.start()
  timer.join()
  print("This should execute")

this_should_start_then_wait()

def lambda_handler(event, context):
    return this_should_start_then_wait()

Produces this output:

This starts
Hello User
b a
This should execute
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.