asyncexecutor.py 868 B

123456789101112131415161718192021222324252627282930313233343536
  1. """ An simple lightweight asynchronous executor class with nice
  2. java type static methods """
  3. from twisted.python.threadpool import ThreadPool
  4. class AsyncExecutor(object):
  5. """ defaults to minthreads=5, maxthreads=20 """
  6. pool = ThreadPool( name = 'AsyncExecutorPool')
  7. def _execute(self, func, *args, **kwargs):
  8. if not self.pool.started:
  9. self.pool.start()
  10. self.pool.dispatch(None, func, *args, **kwargs)
  11. execute = classmethod(_execute)
  12. stop = pool.stop
  13. def test():
  14. import random
  15. import time
  16. def test(digit):
  17. print 'Testing %d' % digit
  18. time.sleep(random.randint(1, 5000)/1000)
  19. print ' finished with test %d' % digit
  20. for i in xrange(10):
  21. AsyncExecutor.execute(test, )
  22. AsyncExecutor.stop()
  23. if __name__ == '__main__':
  24. test()