python.lang.correctness.sync-sleep-in-async-code.sync-sleep-in-async-code

profile photo of semgrepsemgrep
Author
unknown
Download Count*

Synchronous time.sleep in async code will block the event loop and not allow other tasks to execute. Use asyncio.sleep() instead.

Run Locally

Run in CI

Defintion

rules:
  - id: sync-sleep-in-async-code
    patterns:
      - pattern: time.sleep(...)
      - pattern-inside: |
          async def $F(...):
            ...
      - pattern-not-inside: |
          async def $F(...):
            def $INNER(...):
              ...
    message: Synchronous time.sleep in async code will block the event loop and not
      allow other tasks to execute. Use asyncio.sleep() instead.
    languages:
      - python
    severity: WARNING
    metadata:
      category: best-practice
      technology:
        - python
      license: Commons Clause License Condition v1.0[LGPL-2.1-only]

Examples

sync-sleep-in-async-code.py

import time

async def bad_code():
  for i in range(10):
    # ruleid:sync-sleep-in-async-code
    time.sleep(1)


async def good_code():
  await asyncio.sleep(1)

def sync_sleep():
  # ok:sync-sleep-in-async-code
  time.sleep(1)

# should not match
async def nested():
  def nested_sync():
    # ok:sync-sleep-in-async-code
    time.sleep(1)

def nested2():
  async def inner():
    # ruleid:sync-sleep-in-async-code
    time.sleep(1)

  # ok:sync-sleep-in-async-code
  time.sleep(1)