Raghav salotra
Raghav salotra

Reputation: 871

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?

Upvotes: 2

Views: 2710

Answers (2)

Jack
Jack

Reputation: 902

There is an experimental function you can use now : wait_for_termination()

server.add_insecure_port('[::]:50051')
server.start()
server.wait_for_termination()

Block current thread until the server stops.

This is an EXPERIMENTAL API.

The wait will not consume computational resources during blocking, and it will block until one of the two following conditions are met:

  1. The server is stopped or terminated;
  2. A timeout occurs if timeout is not None.

Upvotes: 0

Eric G
Eric G

Reputation: 4058

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.

Upvotes: 5

Related Questions