The ListeningThread class

Our ListeningThread class will need to inherit from threading.Thread and contain a run method, which can happen in the background.

Since we want to be always checking for new messages until the user closes their ChatWindow, we shall put our request inside a loop which the ChatWindow will be able to end when closed.

Let's begin our ListeningThread class, as follows:

import arrow
import threading
import time

from requester import Requester

Our class will be making use of the following modules:

  • arrow: This is used to create the timestamps
  • threading: This is used to run in the background
  • time: This is used to sleep for two seconds between requests
  • requester: This is used to contact our web service

With the imports taken care of, we can begin writing the class.

class ListeningThread(threading.Thread):
def __init__(self, master, user_one, user_two):
super().__init__()
self.master = master
self.user_one = user_one
self.user_two = user_two
self.requester = Requester()
self.running = True
self.last_checked_time = arrow.now().timestamp

Our __init__ method will create a few attributes. These do the following:

  • master: This refers to our ChatWindow widget and will be used later to handle stopping the thread's infinite loop when the window is closed
  • user_one: The logged-in user of the application
  • user_two: The friend they are messaging
  • requester: Our Requester object
  • running: A variable which is used to begin and end the loop
  • last_checked_time: The timestamp sent to our web service to determine what messages we have and have not seen

We are now prepared to write the run method, which will be called when this class is started:

def run(self):
while self.running:
new_messages = self.requester.get_new_messages(self.last_checked_time, self.user_one, self.user_two)
self.last_checked_time = arrow.now().timestamp
for message in new_messages['messages']:
self.master.receive_message(message["author"],
message["message"])

time.sleep(2)

del self.master.listening_thread

return

In order to run in a constant loop, we use a while loop combined with our running attribute. This way, in order to cancel the loop, we just need to set the thread instance's running attribute to False.

When in the loop, the thread is calling the get_new_messages endpoint, updating its last_checked_time, then passing any returned messages over to the ChatWindow's receive_message method.

After each iteration, the thread will wait for two seconds before repeating.

When the loop is stopped, the thread will delete the listening_thread attribute from our ChatWindow class, then return to exit the method. We will see why this happens shortly.

This completes our ListeningThread class. We can now import and implement it in our ChatWindow to get new messages coming in.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset