How to create simultaneous delays in python

42 Views Asked by At

I'm creating a supermarket simulation where:

  • There are multiple lanes.
  • Customers are being generated simultaneously.
  • Customers baskets are being processed simultaneously.

My problem as of now is that, of course I want to create delays for when customers are processing their items and which the delay is calculated by how large their basket is. Below is sample data of what it looks like:

{
  "Customer 2": {
    "CustomerID": "C2",
    "Items In Basket": 14,
    "Lane Type": "Cashier",
    "Process Time": 84
  },
  "Customer 4": {
    "CustomerID": "C4",
    "Items In Basket": 14,
    "Lane Type": "Cashier",
    "Process Time": 84
  },
  "Customer 7": {
    "CustomerID": "C7",
    "Items In Basket": 15,
    "Lane Type": "Cashier",
    "Process Time": 90
  },
  "Customer 5": {
    "CustomerID": "C5",
    "Items In Basket": 19,
    "Lane Type": "Cashier",
    "Process Time": 114
  }
}

The code in use for the delay (in seconds) is:

    def ProcessItems(self):
        Customers_In_Cashier = self.ExtractCustomerData()
        for keys in Customers_In_Cashier:
            delays = (Customers_In_Cashier[keys]["Process Time"])
            time.sleep(delays)
            print(f"Customer {Customers_In_Cashier[keys]["CustomerID"]} time has been completed.")

However, the issue is that because of the time.sleep() the rest of the simulation comes to a halt until the delay has been finished. Ideally, I would want other parts of the program to run along with running simultaneous delays as well as there will be more than one customer at a time processing their items.

Is there a way to have a delay but for only certain parts of the code?

I have tried using asyncio but I didn't really come to an understanding of how it functions. So I am just looking for other ways this can be dealt with or to be educated on how asyncio function would work in this scenario.

0

There are 0 best solutions below