Search code examples
pythongrpc

Is it posible to keep a gRPC server alive without using a sleep condition?


Please refer the below code:

import grpc

from concurrent import futures
import time

import calculator_pb2
import calculator_pb2_grpc
import calculator

class CalculatorServicer(calculator_pb2_grpc.CalculatorServicer):

    def SquareRoot(selfself, request, context):
        response = calculator_pb2.Number()
        response.value = calculator.square_root((request.value))
        return response

# Creating gRPC server
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))

calculator_pb2_grpc.add_CalculatorServicer_to_server(CalculatorServicer(), server)

print('Starting server. Listening on port 50051.')
server.add_insecure_port('[::]:50051')
server.start()

# The below line is what is keeping the server alive
try:
     while True:
         time.sleep(86400)
except KeyboardInterrupt:
    server.stop(0)

**********************************

try:
     while True:
         time.sleep(86400)
except KeyboardInterrupt:
    server.stop(0)

***********************************

In the above code block, is it possible to not to using a sleep condition and still the server will be alive?


Solution

  • Currently gRPC Python servers do not have an equivalent to the C++ server's Wait() API. You will need to keep the calls to Python's time.sleep, as in our example server code.