11import json
22import logging
3- import threading
43import time
54from .config .topic_config import Config
6- from .abstract .topic_abstract import TopicAbstract
75from ..resource_errors import ExceptionHandler
6+ from concurrent .futures import ThreadPoolExecutor
7+ from .abstract .topic_abstract import TopicAbstract
88from ..queue .models .queue_message import QueueMessage
99
1010logging .basicConfig (format = '%(asctime)s %(levelname)-8s %(message)s' , datefmt = '%Y-%m-%d %H:%M:%S' )
@@ -18,6 +18,7 @@ def __init__(self, fn=None, max_concurrent_messages=1):
1818 self ._max_concurrent_messages = max_concurrent_messages
1919 self ._renewal_interval = 30 # seconds
2020 self .message_processing = 0
21+ self .executor = ThreadPoolExecutor (max_workers = max_concurrent_messages )
2122
2223 def _renew_message_lock (self , message , receiver ):
2324 while True :
@@ -31,12 +32,9 @@ def _renew_message_lock(self, message, receiver):
3132 # Sends data to the callback function
3233 def process_message (self , message , receiver ):
3334 queue_message = QueueMessage .data_from (str (message ))
35+ secondary_executor = ThreadPoolExecutor (max_workers = 1 )
3436 if not message ._lock_expired :
35- lock_renewal_thread = threading .Thread (
36- target = self ._renew_message_lock ,
37- args = (message , receiver )
38- )
39- lock_renewal_thread .start ()
37+ secondary_executor .submit (self ._renew_message_lock , message , receiver )
4038 self ._function_to_call (queue_message )
4139
4240 # Starts listening to the messages
@@ -61,9 +59,7 @@ def start_listening(self, provider, topic, subscription):
6159 continue
6260 for message in messages :
6361 self .message_processing += 1
64- threading .Thread (
65- target = self ._process_message_in_thread ,
66- args = (message , topic_receiver ,)).start ()
62+ self .executor .submit (self ._process_message_in_thread , message , topic_receiver )
6763 except Exception as et :
6864 logger .error (f'Error in service bus connection: { et } ' )
6965 else :
@@ -94,9 +90,7 @@ def __init__(self, config=None, topic_name=None, max_concurrent_messages=1):
9490 def subscribe (self , subscription = None , callback = None ):
9591 if subscription is not None :
9692 cb = Callback (callback , max_concurrent_messages = self .max_concurrent_messages )
97- thread = threading .Thread (target = cb .start_listening , args = (self .provider , self .topic , subscription ))
98- thread .start ()
99- time .sleep (5 )
93+ cb .start_listening (self .provider , self .topic , subscription )
10094 else :
10195 logging .error (
10296 f'Unimplemented initialize for core { self .provider .provider } , Subscription name is required!' )
0 commit comments