asyncio run two different functions periodically with different intervals





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







1















Would it be possible using asyncio to run 2 different functions periodically with different interval for each function f forever?



If yes - could you please provide code example.



import asyncio

async def f1(host,*arg):
# call every 1 sec
pass

async def f2(url,*args):
# call every 2 sec
pass


Expected output:



00:00 f1 for 1.1.1.1

00:01 f1 for 1.1.1.1

00:02 f2 for 'google.com'

00:02 f1 for 1.1.1.1

00:03 f1 for 1.1.1.1

00:04 f2 for 'google.com'









share|improve this question































    1















    Would it be possible using asyncio to run 2 different functions periodically with different interval for each function f forever?



    If yes - could you please provide code example.



    import asyncio

    async def f1(host,*arg):
    # call every 1 sec
    pass

    async def f2(url,*args):
    # call every 2 sec
    pass


    Expected output:



    00:00 f1 for 1.1.1.1

    00:01 f1 for 1.1.1.1

    00:02 f2 for 'google.com'

    00:02 f1 for 1.1.1.1

    00:03 f1 for 1.1.1.1

    00:04 f2 for 'google.com'









    share|improve this question



























      1












      1








      1








      Would it be possible using asyncio to run 2 different functions periodically with different interval for each function f forever?



      If yes - could you please provide code example.



      import asyncio

      async def f1(host,*arg):
      # call every 1 sec
      pass

      async def f2(url,*args):
      # call every 2 sec
      pass


      Expected output:



      00:00 f1 for 1.1.1.1

      00:01 f1 for 1.1.1.1

      00:02 f2 for 'google.com'

      00:02 f1 for 1.1.1.1

      00:03 f1 for 1.1.1.1

      00:04 f2 for 'google.com'









      share|improve this question
















      Would it be possible using asyncio to run 2 different functions periodically with different interval for each function f forever?



      If yes - could you please provide code example.



      import asyncio

      async def f1(host,*arg):
      # call every 1 sec
      pass

      async def f2(url,*args):
      # call every 2 sec
      pass


      Expected output:



      00:00 f1 for 1.1.1.1

      00:01 f1 for 1.1.1.1

      00:02 f2 for 'google.com'

      00:02 f1 for 1.1.1.1

      00:03 f1 for 1.1.1.1

      00:04 f2 for 'google.com'






      python-3.x python-asyncio






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 16 '18 at 15:32









      mrk

      2,34311737




      2,34311737










      asked Nov 16 '18 at 14:37









      unevenuneven

      82




      82
























          1 Answer
          1






          active

          oldest

          votes


















          1















          Would it be possible using asyncio to run 2 different functions periodically with different interval for each f forever ?




          Sure, just create a coroutine that does it in the "obvious" way, by awaiting the coroutine in an infinite loop with asyncio.sleep() between invocations:



          import asyncio, time

          async def invoke_forever(period, corofn, *args):
          while True:
          then = time.time()
          await corofn(*args)
          elapsed = time.time() - then
          await asyncio.sleep(period - elapsed)


          Scenario described in the question would be set up with something like:



          loop = asyncio.get_event_loop()
          loop.create_task(invoke_forever(1, f1, 'host1'))
          loop.create_task(invoke_forever(2, f2, 'host2'))
          loop.run_forever()


          You can also call asyncio.gather to combine the two invoke_forever into one awaitable, which allows using the asyncio.run function introduced in Python 3.7:



          asyncio.run(asyncio.gather(
          invoke_forever(1, f1, 'host1'),
          invoke_forever(2, f2, 'host2')))





          share|improve this answer



















          • 1





            Hat's off !!! - works like a charm. Indeed i tried in the meantime using ensure_future combined with gather adding while loop in each f1,f2..but i like your solution more..(did not came to the point to add worker in the middle like you did. I am on 3.6, so i did not tried "run" method....Thank You !!!

            – uneven
            Nov 16 '18 at 16:28











          • Is there a way to include "timeout" for each task?. I tired asyncio.wait_for. I can't make it working in such a scenarios (above) as it stops all tasks after given timeout value.

            – uneven
            Nov 16 '18 at 17:17











          • @uneven Have you tried replacing await corofn(*args) with await asyncio.wait_for( corofn(*args)), perhaps with a try/except TimeoutError if you want to continue after a timeout?

            – user4815162342
            Nov 16 '18 at 17:23






          • 1





            Simple and efficient - You made my day/weekend Sir - Thanks a million !!!

            – uneven
            Nov 16 '18 at 18:53












          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53339921%2fasyncio-run-two-different-functions-periodically-with-different-intervals%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1















          Would it be possible using asyncio to run 2 different functions periodically with different interval for each f forever ?




          Sure, just create a coroutine that does it in the "obvious" way, by awaiting the coroutine in an infinite loop with asyncio.sleep() between invocations:



          import asyncio, time

          async def invoke_forever(period, corofn, *args):
          while True:
          then = time.time()
          await corofn(*args)
          elapsed = time.time() - then
          await asyncio.sleep(period - elapsed)


          Scenario described in the question would be set up with something like:



          loop = asyncio.get_event_loop()
          loop.create_task(invoke_forever(1, f1, 'host1'))
          loop.create_task(invoke_forever(2, f2, 'host2'))
          loop.run_forever()


          You can also call asyncio.gather to combine the two invoke_forever into one awaitable, which allows using the asyncio.run function introduced in Python 3.7:



          asyncio.run(asyncio.gather(
          invoke_forever(1, f1, 'host1'),
          invoke_forever(2, f2, 'host2')))





          share|improve this answer



















          • 1





            Hat's off !!! - works like a charm. Indeed i tried in the meantime using ensure_future combined with gather adding while loop in each f1,f2..but i like your solution more..(did not came to the point to add worker in the middle like you did. I am on 3.6, so i did not tried "run" method....Thank You !!!

            – uneven
            Nov 16 '18 at 16:28











          • Is there a way to include "timeout" for each task?. I tired asyncio.wait_for. I can't make it working in such a scenarios (above) as it stops all tasks after given timeout value.

            – uneven
            Nov 16 '18 at 17:17











          • @uneven Have you tried replacing await corofn(*args) with await asyncio.wait_for( corofn(*args)), perhaps with a try/except TimeoutError if you want to continue after a timeout?

            – user4815162342
            Nov 16 '18 at 17:23






          • 1





            Simple and efficient - You made my day/weekend Sir - Thanks a million !!!

            – uneven
            Nov 16 '18 at 18:53
















          1















          Would it be possible using asyncio to run 2 different functions periodically with different interval for each f forever ?




          Sure, just create a coroutine that does it in the "obvious" way, by awaiting the coroutine in an infinite loop with asyncio.sleep() between invocations:



          import asyncio, time

          async def invoke_forever(period, corofn, *args):
          while True:
          then = time.time()
          await corofn(*args)
          elapsed = time.time() - then
          await asyncio.sleep(period - elapsed)


          Scenario described in the question would be set up with something like:



          loop = asyncio.get_event_loop()
          loop.create_task(invoke_forever(1, f1, 'host1'))
          loop.create_task(invoke_forever(2, f2, 'host2'))
          loop.run_forever()


          You can also call asyncio.gather to combine the two invoke_forever into one awaitable, which allows using the asyncio.run function introduced in Python 3.7:



          asyncio.run(asyncio.gather(
          invoke_forever(1, f1, 'host1'),
          invoke_forever(2, f2, 'host2')))





          share|improve this answer



















          • 1





            Hat's off !!! - works like a charm. Indeed i tried in the meantime using ensure_future combined with gather adding while loop in each f1,f2..but i like your solution more..(did not came to the point to add worker in the middle like you did. I am on 3.6, so i did not tried "run" method....Thank You !!!

            – uneven
            Nov 16 '18 at 16:28











          • Is there a way to include "timeout" for each task?. I tired asyncio.wait_for. I can't make it working in such a scenarios (above) as it stops all tasks after given timeout value.

            – uneven
            Nov 16 '18 at 17:17











          • @uneven Have you tried replacing await corofn(*args) with await asyncio.wait_for( corofn(*args)), perhaps with a try/except TimeoutError if you want to continue after a timeout?

            – user4815162342
            Nov 16 '18 at 17:23






          • 1





            Simple and efficient - You made my day/weekend Sir - Thanks a million !!!

            – uneven
            Nov 16 '18 at 18:53














          1












          1








          1








          Would it be possible using asyncio to run 2 different functions periodically with different interval for each f forever ?




          Sure, just create a coroutine that does it in the "obvious" way, by awaiting the coroutine in an infinite loop with asyncio.sleep() between invocations:



          import asyncio, time

          async def invoke_forever(period, corofn, *args):
          while True:
          then = time.time()
          await corofn(*args)
          elapsed = time.time() - then
          await asyncio.sleep(period - elapsed)


          Scenario described in the question would be set up with something like:



          loop = asyncio.get_event_loop()
          loop.create_task(invoke_forever(1, f1, 'host1'))
          loop.create_task(invoke_forever(2, f2, 'host2'))
          loop.run_forever()


          You can also call asyncio.gather to combine the two invoke_forever into one awaitable, which allows using the asyncio.run function introduced in Python 3.7:



          asyncio.run(asyncio.gather(
          invoke_forever(1, f1, 'host1'),
          invoke_forever(2, f2, 'host2')))





          share|improve this answer














          Would it be possible using asyncio to run 2 different functions periodically with different interval for each f forever ?




          Sure, just create a coroutine that does it in the "obvious" way, by awaiting the coroutine in an infinite loop with asyncio.sleep() between invocations:



          import asyncio, time

          async def invoke_forever(period, corofn, *args):
          while True:
          then = time.time()
          await corofn(*args)
          elapsed = time.time() - then
          await asyncio.sleep(period - elapsed)


          Scenario described in the question would be set up with something like:



          loop = asyncio.get_event_loop()
          loop.create_task(invoke_forever(1, f1, 'host1'))
          loop.create_task(invoke_forever(2, f2, 'host2'))
          loop.run_forever()


          You can also call asyncio.gather to combine the two invoke_forever into one awaitable, which allows using the asyncio.run function introduced in Python 3.7:



          asyncio.run(asyncio.gather(
          invoke_forever(1, f1, 'host1'),
          invoke_forever(2, f2, 'host2')))






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 16 '18 at 15:27









          user4815162342user4815162342

          64.7k595151




          64.7k595151








          • 1





            Hat's off !!! - works like a charm. Indeed i tried in the meantime using ensure_future combined with gather adding while loop in each f1,f2..but i like your solution more..(did not came to the point to add worker in the middle like you did. I am on 3.6, so i did not tried "run" method....Thank You !!!

            – uneven
            Nov 16 '18 at 16:28











          • Is there a way to include "timeout" for each task?. I tired asyncio.wait_for. I can't make it working in such a scenarios (above) as it stops all tasks after given timeout value.

            – uneven
            Nov 16 '18 at 17:17











          • @uneven Have you tried replacing await corofn(*args) with await asyncio.wait_for( corofn(*args)), perhaps with a try/except TimeoutError if you want to continue after a timeout?

            – user4815162342
            Nov 16 '18 at 17:23






          • 1





            Simple and efficient - You made my day/weekend Sir - Thanks a million !!!

            – uneven
            Nov 16 '18 at 18:53














          • 1





            Hat's off !!! - works like a charm. Indeed i tried in the meantime using ensure_future combined with gather adding while loop in each f1,f2..but i like your solution more..(did not came to the point to add worker in the middle like you did. I am on 3.6, so i did not tried "run" method....Thank You !!!

            – uneven
            Nov 16 '18 at 16:28











          • Is there a way to include "timeout" for each task?. I tired asyncio.wait_for. I can't make it working in such a scenarios (above) as it stops all tasks after given timeout value.

            – uneven
            Nov 16 '18 at 17:17











          • @uneven Have you tried replacing await corofn(*args) with await asyncio.wait_for( corofn(*args)), perhaps with a try/except TimeoutError if you want to continue after a timeout?

            – user4815162342
            Nov 16 '18 at 17:23






          • 1





            Simple and efficient - You made my day/weekend Sir - Thanks a million !!!

            – uneven
            Nov 16 '18 at 18:53








          1




          1





          Hat's off !!! - works like a charm. Indeed i tried in the meantime using ensure_future combined with gather adding while loop in each f1,f2..but i like your solution more..(did not came to the point to add worker in the middle like you did. I am on 3.6, so i did not tried "run" method....Thank You !!!

          – uneven
          Nov 16 '18 at 16:28





          Hat's off !!! - works like a charm. Indeed i tried in the meantime using ensure_future combined with gather adding while loop in each f1,f2..but i like your solution more..(did not came to the point to add worker in the middle like you did. I am on 3.6, so i did not tried "run" method....Thank You !!!

          – uneven
          Nov 16 '18 at 16:28













          Is there a way to include "timeout" for each task?. I tired asyncio.wait_for. I can't make it working in such a scenarios (above) as it stops all tasks after given timeout value.

          – uneven
          Nov 16 '18 at 17:17





          Is there a way to include "timeout" for each task?. I tired asyncio.wait_for. I can't make it working in such a scenarios (above) as it stops all tasks after given timeout value.

          – uneven
          Nov 16 '18 at 17:17













          @uneven Have you tried replacing await corofn(*args) with await asyncio.wait_for( corofn(*args)), perhaps with a try/except TimeoutError if you want to continue after a timeout?

          – user4815162342
          Nov 16 '18 at 17:23





          @uneven Have you tried replacing await corofn(*args) with await asyncio.wait_for( corofn(*args)), perhaps with a try/except TimeoutError if you want to continue after a timeout?

          – user4815162342
          Nov 16 '18 at 17:23




          1




          1





          Simple and efficient - You made my day/weekend Sir - Thanks a million !!!

          – uneven
          Nov 16 '18 at 18:53





          Simple and efficient - You made my day/weekend Sir - Thanks a million !!!

          – uneven
          Nov 16 '18 at 18:53




















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53339921%2fasyncio-run-two-different-functions-periodically-with-different-intervals%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Bressuire

          Vorschmack

          Quarantine