Best way to implement a non-blocking wait?

Viewed 17413

In python, if I want to keep a process or thread running forever, I can typically do this with an empty while loop:

while 1:
    pass

This, however, will eat an unfair amount of CPU process. Adding a short sleep would work:

import time
while 1:
    time.sleep(0.01)

Is there any best or cleaner way of doing this?

5 Answers

Someone might end up to this old question so I'll be leaving this here. The optimal way is a BlockingScheduler from apscheduler module with which you also get to schedule jobs in regular intervals (or cron like or whatever)

from datetime import datetime
import os

from apscheduler.schedulers.blocking import BlockingScheduler


def tick():
    print('Tick! The time is: %s' % datetime.now())


if __name__ == '__main__':
    scheduler = BlockingScheduler()
    scheduler.add_job(tick, 'interval', seconds=3)
    print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C'))

    try:
        scheduler.start()
    except (KeyboardInterrupt, SystemExit):
        pass
Related