Kitware / wslink

Python/JavaScript library for communicating over WebSocket
https://kitware.github.io/wslink/
BSD 3-Clause "New" or "Revised" License
83 stars 27 forks source link

Add loop task methods for callbacks and coroutines #71

Open scottwittenburg opened 3 years ago

scottwittenburg commented 3 years ago

When wslink made use of twisted, we had a example that did:

from twisted.internet import task
...
loopTask = task.LoopingCall(callback_method)
loopTask.start(2.0)

and that would schedule callback_method to be called repeatedly every two seconds. We can achieve something similar with just the schedule_callback method in wslink now, but not as simply. It would be nice to provide this capability. A first pass at it might look like:

    def loop_callback(period, callback, *args, **kwargs):
       cancel_handle = None
       canceled = False
       func = functools.partial(callback, *args, **kwargs)
       loop = asyncio.get_running_loop()

       def cancel():
          global canceled

          cancel_handle.cancel()
          canceled = True

       def task():
          global cancel_handle

          if not canceled:
             func()
             cancel_handle = loop.call_later(period, task)

       cancel_handle = loop.call_later(period, task)

       return cancel

Though it would be nice if the return value was an object with a cancel() method, so it behaves like the other scheduling methods.