{"id":5816,"date":"2020-05-18T21:20:30","date_gmt":"2020-05-18T21:20:30","guid":{"rendered":"https:\/\/www.askpython.com\/?p=5816"},"modified":"2022-07-07T07:08:03","modified_gmt":"2022-07-07T07:08:03","slug":"python-wait-for-a-specific-time","status":"publish","type":"post","link":"https:\/\/www.askpython.com\/python\/examples\/python-wait-for-a-specific-time","title":{"rendered":"How to Wait for a Specific Time in Python?"},"content":{"rendered":"\n<p>Hello everyone! In this post, we&#8217;ll look at how we can wait for a specific time in Python.<\/p>\n\n\n\n<p>This is particularly important when you have certain events or tasks scheduled after a specific period of time.<\/p>\n\n\n\n<p>Python offers us different ways to do this. So let&#8217;s look at all the approaches that we can use: both in a single-threaded as well as a multi-threaded environment!<\/p>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Python &#8211; Wait for a Specific Time in Single-Threaded Environments<\/h2>\n\n\n\n<p>If your main program consists only of a single thread \/ program, then Python makes this very easy for us.<\/p>\n\n\n\n<p>One possible approach to make a program wait for a specific time in Python  is using the <strong><a href=\"https:\/\/www.askpython.com\/python-modules\/python-time-module\" class=\"rank-math-link\">time <\/a><\/strong>module.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Using time.sleep() to wait<\/h3>\n\n\n\n<p>We can use <code>time.sleep(n)<\/code> to wait for <code>n<\/code> seconds. Of course, we can make <code>n<\/code> to be decimal to be more precise with our interval!<\/p>\n\n\n\n<p>Here is a simple example, which schedules two function calls between 3 seconds within each other.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport time\n\ndef fun1(a):\n    return 2 * a\n\ndef fun2(a):\n    return a * a\n\nif __name__ == &#039;__main__&#039;:\n    inp = 10\n    print(f&quot;Input = {inp}&quot;)\n    print(f&quot;Result of fun1 call: {fun1(inp)}&quot;)\n    time.sleep(3) # Wait for 3 seconds\n    print(f&quot;After 3 milliseconds, Result of fun2 call: {fun2(inp)}&quot;)\n<\/pre><\/div>\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\nInput = 10\nResult of fun1 call: 20\nAfter 3 seconds, Result of fun2 call: 100\n<\/pre><\/div>\n\n\n<p>Simple enough, right?<\/p>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Waiting in a Multi-Threaded Environment<\/h2>\n\n\n\n<p>If you&#8217;re having multiple threads in your program, you can still use the same logic via <code>time.sleep()<\/code> to make a particular thread wait for a specific time in Python<\/p>\n\n\n\n<p>Here is an example, which spawns 3 threads, and makes them sleep for a second alternatively, while the other threads keep printing numbers from 1.<\/p>\n\n\n\n<p>We&#8217;ll use the <code>concurrent.futures<\/code> module and use the <code>ThreadPoolExecutor<\/code> to pool and execute threads, while fetching the results using <code>as_completed()<\/code>.<\/p>\n\n\n\n<p>The basic structure of spawning and fetching using threads is as follows:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nfrom concurrent.futures import ThreadPoolExecutor, as_completed\n\n# The threads will call this function\ndef callback():\n    pass\n\nwith ThreadPoolExecutor() as thread_executor:\n    # Await all results\n    await_results = &#x5B;thread_executor.submit(callback) for i in range(1, tid+1)]\n    # Fetch them!\n    for f in as_completed(&#x5B;future for future in await_results]):\n        print(f.result())\n<\/pre><\/div>\n\n\n<p>Now, let&#8217;s write the code for our main program.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nfrom concurrent.futures import ThreadPoolExecutor, as_completed\nimport time\n\n# Global Variable for the Thread ID Number\ntid = 0\n# Spawn 4 threads\nNUM_THREADS = 4\n\ndef func(arg):\n    time.sleep(1)\n    return arg * arg\n\nif __name__ == &#039;__main__&#039;:\n    with ThreadPoolExecutor() as thread_executor:\n        start_time = time.time()\n        # Going to spawn threads\n        tid += NUM_THREADS\n        # Await all results\n        await_results = &#x5B;thread_executor.submit(func, arg=i) for i in range(1, tid+1)]\n        for f in as_completed(&#x5B;future for future in await_results]):\n            print(f.result())\n        end_time = time.time()\n        print(f&quot;Total Time taken for {NUM_THREADS} threads: {end_time - start_time}&quot;)\n<\/pre><\/div>\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\n1\n4\n9\n16\nTotal Time taken for 4 threads: 1.0037879943847656\n<\/pre><\/div>\n\n\n<p>As you can see, we spawned 4 threads, who all waited for 1 second before giving the result of the function. This is very close to 1 second, so our output makes sense!<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Using threading.Timer() to schedule function calls<\/h3>\n\n\n\n<p>However, if you want a particular function to wait for a specific time in Python, we can use the <code>threading.Timer()<\/code> method from the <code>threading<\/code> module.<\/p>\n\n\n\n<p>We&#8217;ll show a simple example, which schedules a function call every 5 seconds.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nfrom threading import Timer\nimport time\n\ndef func(a, b):\n    print(&quot;Called function&quot;)\n    return a * b\n\n# Schedule a timer for 5 seconds\n# We pass arguments 3 and 4\nt = Timer(5.0, func, &#x5B;3, 4])\n\nstart_time = time.time()\n\n# Start the timer\nt.start()\n\nend_time = time.time()\n\nif end_time - start_time &lt; 5.0:\n    print(&quot;Timer will wait for sometime before calling the function&quot;)\nelse:\n    print(&quot;5 seconds already passed. Timer finished calling func()&quot;)\n<\/pre><\/div>\n\n\n<p><strong>Output<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: plain; title: ; notranslate\" title=\"\">\nTimer will wait for sometime before calling the function\nCalled function\n<\/pre><\/div>\n\n\n<p>Here, the main program came to the last line before 5 seconds were up, so Timer makes the program wait until it calls <code>func()<\/code>.<\/p>\n\n\n\n<p>After calling <code>func(a, b)<\/code>, it terminates the program, since there is nothing else to run.<\/p>\n\n\n\n<p>Also notice that the return value of the function cannot be used by the main program.<\/p>\n\n\n\n<p>Hopefully, this gave you some more ideas about scheduling and waiting for intervals.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p>In this article, we learned about waiting for a specific period of time in Python, using <code>time.sleep()<\/code>. We also saw how we could use this in a Multi-Threaded environment, as well as scheduling function calls.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">References<\/h2>\n\n\n\n<ul class=\"wp-block-list\"><li><a href=\"https:\/\/docs.python.org\/3\/library\/threading.html#timer-objects\" class=\"rank-math-link\" target=\"_blank\" rel=\"noopener\">Python Docs<\/a> on Threading Timer<\/li><li><a href=\"https:\/\/stackoverflow.com\/questions\/510348\/how-do-i-make-a-time-delay\" class=\"rank-math-link\" target=\"_blank\" rel=\"noopener\">StackOverflow Question<\/a> on creating time delays<\/li><\/ul>\n\n\n\n<hr class=\"wp-block-separator has-text-color has-background has-vivid-green-cyan-background-color has-vivid-green-cyan-color\"\/>\n","protected":false},"excerpt":{"rendered":"<p>Hello everyone! In this post, we&#8217;ll look at how we can wait for a specific time in Python. This is particularly important when you have certain events or tasks scheduled after a specific period of time. Python offers us different ways to do this. So let&#8217;s look at all the approaches that we can use: [&hellip;]<\/p>\n","protected":false},"author":7,"featured_media":5824,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[9],"tags":[],"class_list":["post-5816","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-examples"],"blocksy_meta":[],"_links":{"self":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/5816","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/users\/7"}],"replies":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/comments?post=5816"}],"version-history":[{"count":0,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/5816\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media\/5824"}],"wp:attachment":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media?parent=5816"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/categories?post=5816"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/tags?post=5816"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}