{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<small><small><i>\n",
    "All the IPython Notebooks in **Python Date Time Module** lecture series by Dr. Milaan Parmar are available @ **[GitHub](https://github.com/milaan9/08_Python_Date_Time_Module)**\n",
    "</i></small></small>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Python `sleep()`\n",
    "\n",
    "The **`sleep()`** function suspends (waits) execution of the current thread for a given number of seconds.\n",
    "\n",
    "Python has a module named **[time](https://github.com/milaan9/08_Python_Date_Time_Module/blob/main/007_Python_time_Module.ipynb)** which provides several useful functions to handle time-related tasks. One of the popular functions among them is **`sleep()`**.\n",
    "\n",
    "The **`sleep()`** function suspends execution of the current thread for a given number of seconds."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Example 1: Python `sleep()`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-06-22T14:03:34.387197Z",
     "start_time": "2021-06-22T14:03:31.941423Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Printed immediately.\n",
      "Printed after 2.4 seconds.\n"
     ]
    }
   ],
   "source": [
    "# Example 1: Python sleep()\n",
    "\n",
    "import time\n",
    "\n",
    "print(\"Printed immediately.\")\n",
    "time.sleep(2.4)\n",
    "print(\"Printed after 2.4 seconds.\")\n",
    "\n",
    "# When you run the program, the output will be like below:"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Explanation:** \n",
    "\n",
    "* **`\"Printed immediately\"`** is printed\n",
    "* Suspends (Delays) execution for 2.4 seconds.\n",
    "* **`\"Printed after 2.4 seconds\"`** is printed.\n",
    "\n",
    "As you can see from the above example, **`sleep()`** takes a floating-point number as an argument.\n",
    "\n",
    "**Before Python 3.5**, the actual suspension time may be less than the argument specified to the **`time()`** function.\n",
    "\n",
    "**Since Python 3.5**, the suspension time will be at least the seconds specified."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In the below program, we computed and printed the current local time inside the infinite **[while loop](https://github.com/milaan9/03_Python_Flow_Control/blob/main/006_Python_while_Loop.ipynb)**. Then, the program waits for 1 second. Again, the current local time is computed and printed. This process goes on."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Example 2: Python create a digital clock"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-06-22T14:04:28.272481Z",
     "start_time": "2021-06-22T14:03:39.637159Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "07:33:39 PM\n",
      "07:33:40 PM\n",
      "07:33:41 PM\n",
      "07:33:42 PM\n",
      "07:33:43 PM\n",
      "07:33:44 PM\n",
      "07:33:45 PM\n",
      "07:33:46 PM\n",
      "07:33:47 PM\n",
      "07:33:48 PM\n",
      "07:33:49 PM\n",
      "07:33:50 PM\n",
      "07:33:51 PM\n",
      "07:33:52 PM\n",
      "07:33:53 PM\n",
      "07:33:54 PM\n",
      "07:33:55 PM\n",
      "07:33:56 PM\n",
      "07:33:57 PM\n",
      "07:33:58 PM\n",
      "07:33:59 PM\n",
      "07:34:00 PM\n",
      "07:34:01 PM\n",
      "07:34:02 PM\n",
      "07:34:03 PM\n",
      "07:34:04 PM\n",
      "07:34:05 PM\n",
      "07:34:06 PM\n",
      "07:34:07 PM\n",
      "07:34:08 PM\n",
      "07:34:09 PM\n",
      "07:34:10 PM\n",
      "07:34:11 PM\n",
      "07:34:12 PM\n",
      "07:34:13 PM\n",
      "07:34:14 PM\n",
      "07:34:15 PM\n",
      "07:34:16 PM\n",
      "07:34:17 PM\n",
      "07:34:18 PM\n",
      "07:34:19 PM\n",
      "07:34:20 PM\n",
      "07:34:21 PM\n",
      "07:34:22 PM\n",
      "07:34:23 PM\n",
      "07:34:24 PM\n",
      "07:34:25 PM\n",
      "07:34:26 PM\n"
     ]
    },
    {
     "ename": "KeyboardInterrupt",
     "evalue": "",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mKeyboardInterrupt\u001b[0m                         Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-2-2f7f4e5fdb49>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[0;32m      7\u001b[0m     \u001b[0mresult\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mtime\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mstrftime\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"%I:%M:%S %p\"\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mlocaltime\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      8\u001b[0m     \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mresult\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 9\u001b[1;33m     \u001b[0mtime\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0msleep\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;36m1\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m     10\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m     11\u001b[0m \u001b[1;31m# When you run the program, the output will be something like below:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;31mKeyboardInterrupt\u001b[0m: "
     ]
    }
   ],
   "source": [
    "# Example 2: Python create a digital clock\n",
    "\n",
    "import time\n",
    "\n",
    "while True:\n",
    "    localtime = time.localtime()\n",
    "    result = time.strftime(\"%I:%M:%S %p\", localtime)\n",
    "    print(result)\n",
    "    time.sleep(1)\n",
    "\n",
    "# When you run the program, the output will be something like below:"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here is a slightly modified better version of the above program."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-06-22T14:04:56.596456Z",
     "start_time": "2021-06-22T14:04:31.238767Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "07:34:55 PM\r"
     ]
    },
    {
     "ename": "KeyboardInterrupt",
     "evalue": "",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mKeyboardInterrupt\u001b[0m                         Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-3-76a0a5ce1450>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[0;32m      6\u001b[0m     \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mresult\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mend\u001b[0m\u001b[1;33m=\u001b[0m\u001b[1;34m\"\"\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mflush\u001b[0m\u001b[1;33m=\u001b[0m\u001b[1;32mTrue\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      7\u001b[0m     \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"\\r\"\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mend\u001b[0m\u001b[1;33m=\u001b[0m\u001b[1;34m\"\"\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mflush\u001b[0m\u001b[1;33m=\u001b[0m\u001b[1;32mTrue\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 8\u001b[1;33m     \u001b[0mtime\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0msleep\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;36m1\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[1;31mKeyboardInterrupt\u001b[0m: "
     ]
    }
   ],
   "source": [
    "import time\n",
    "\n",
    "while True:\n",
    "    localtime = time.localtime()\n",
    "    result = time.strftime(\"%I:%M:%S %p\", localtime)\n",
    "    print(result, end=\"\", flush=True)\n",
    "    print(\"\\r\", end=\"\", flush=True)\n",
    "    time.sleep(1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To learn more, visit **[digital clock in Python shell](https://stackoverflow.com/questions/37515587/run-a-basic-digital-clock-in-the-python-shell)**."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Multithreading in Python\n",
    "\n",
    "Before talking about **`sleep()`** in multithreaded programs, let's talk about processes and threads.\n",
    "\n",
    "A computer program is a collection of instructions. A process is the execution of those instructions.\n",
    "\n",
    "A thread is a subset of the process. A process can have one or more threads."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "All the programs above in this article are single-threaded programs. Here's an example of a multithreaded Python program."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Example 3: Python multithreading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-06-22T14:05:00.232173Z",
     "start_time": "2021-06-22T14:05:00.160880Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hello\n",
      "Hello\n",
      "Hello\n",
      "Hi\n",
      "Hi\n",
      "Hi\n"
     ]
    }
   ],
   "source": [
    "# Example 3: Python multithreading\n",
    "\n",
    "import threading \n",
    "  \n",
    "def print_hello_three_times():\n",
    "    for i in range(3):\n",
    "        print(\"Hello\")\n",
    "\n",
    "def print_hi_three_times(): \n",
    "    for i in range(3): \n",
    "        print(\"Hi\") \n",
    "\n",
    "t1 = threading.Thread(target=print_hello_three_times)  \n",
    "t2 = threading.Thread(target=print_hi_three_times)  \n",
    "\n",
    "t1.start()\n",
    "t2.start()\n",
    "\n",
    "# When you run the program, the output will be something like below:"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Explanation:** The above program has two threads **`t1`** and **`t2`**. These threads are run using **`t1.start()`** and **`t2.start()`** statements.\n",
    "\n",
    ">**Note:** that, **`t1`** and **`t2`** run concurrently and you might get different output.\n",
    "\n",
    "Visit this page to learn more about **[Multithreading in Python](https://stackoverflow.com/questions/2846653/how-can-i-use-threading-in-python)**."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## `time.sleep()` in multithreaded programs\n",
    "\n",
    "The **`sleep()`** function suspends execution of the current thread for a given number of seconds.\n",
    "\n",
    "In case of single-threaded programs, **`sleep()`** suspends execution of the thread and process. However, the function suspends a thread rather than the whole process in multithreaded programs."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Example 4: `sleep()` in a multithreaded program"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-06-22T14:05:15.638783Z",
     "start_time": "2021-06-22T14:05:15.591907Z"
    }
   },
   "outputs": [],
   "source": [
    "# Example 4: sleep() in a multithreaded program\n",
    "\n",
    "import threading \n",
    "import time\n",
    "  \n",
    "def print_hello():\n",
    "    for i in range(4):\n",
    "        time.sleep(0.5)\n",
    "        print(\"Hello\")\n",
    "\n",
    "def print_hi(): \n",
    "    for i in range(4): \n",
    "        time.sleep(0.7)\n",
    "        print(\"Hi\") \n",
    "\n",
    "t1 = threading.Thread(target=print_hello)  \n",
    "t2 = threading.Thread(target=print_hi)  \n",
    "t1.start()\n",
    "t2.start()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Explanation:** The above program has two threads. We have used **`time.sleep(0.5)`** and **`time.sleep(0.75)`** to suspend execution of these two threads for **0.5** seconds and **0.7** seconds respectively."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Recommended Reading:** **[Python time.sleep() sleeps thread](https://stackoverflow.com/questions/92928/time-sleep-sleeps-thread-or-process)**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "hide_input": false,
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.8"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}