Sharvin26
Sharvin26

Reputation: 3101

MultiThreading in AWS lambda using Python3

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.

Upvotes: 10

Views: 12453

Answers (1)

Gabe Hollombe
Gabe Hollombe

Reputation: 8067

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

Upvotes: 14

Related Questions