title: How to create task which sends data continuously and disconnect safely in consumers, django channels 2?
body: <p>From <a href="https://stackoverflow.com/a/51745296/8353711">this</a> answer, which helps to send data from <code>consumers</code> for every <code>n</code> seconds.</p>
  
  <p>Tried to handle the disconnection properly, using <code>creat_task</code> method, tried to stop <code>while-loop</code>(which is used to send data for every <code>n</code> seconds) by sending a <code>flag=False</code>(Assuming, this flag is not sent to the same instance which is created the task). </p>
  
  <p><strong>consumers.py:</strong></p>
  
  <pre><code>class AutoUpdateConsumer(AsyncConsumer):
  
      async def websocket_connect(self, event):
          print("connected", event)
          await self.send({
              "type": "websocket.accept"
          })
          await self.create_task(True)
  
      async def websocket_receive(self, event):
          print("receive", event)
  
      async def websocket_disconnect(self, event):
          await self.create_task(False)
  
          print("disconnected", event)
  
  
      async def create_task(self, flag=True):
          while flag:
              await asyncio.sleep(2)
  
              df= pd.DataFrame(data=[random.sample(range(100), 4) for _ in range(5)])
  
              await self.send({
                  'type': 'websocket.send',
                  'text': df.to_html(),
              })
  </code></pre>
  
  <p><strong>Warning:</strong></p>
  
  <pre><code>2019-09-11 14:40:06,400 - WARNING - server - Application instance 
  &lt;Task pending coro=&lt;SessionMiddlewareInstance.__call__() running at 
  D:\Django\Django channels\django_channels_env\lib\site-packages\channels\sessions.py:175&gt;
  wait_for=&lt;Future pending cb=[&lt;TaskWakeupMethWrapper object at 
  0x000001870E06C618&gt;()] for connection &lt;WebSocketProtocol client=
  ['127.0.0.1', 63789] path=b'/ws/home'&gt; took too long to shut down and was 
  killed.
  </code></pre>
  
  <p>How to stop_task safely instead of waiting for <code>channels</code> to kill task?</p>
  
  <p>Or</p>
  
  <p>How to stop infinite while loop running in a method, from another method in same class?</p>
  
  <p><strong>Versions:</strong></p>
  
  <ul>
  <li>Django == 2.0.7</li>
  <li>channels == 2.1.2</li>
  </ul>