我需要创建一个Runner类,该类可以异步运行多个作业,并在所有作业完成后返回结果。 这是我已经拥有的虚拟代码段
import asyncio
class Runner:
def __init__(self):
self.jobs_loop = asyncio.new_event_loop()
async def slow_process(self, *args):
... # run slow proces with args
await asyncio.sleep(5)
return "result"
def batch_run(self, count, *args):
results = self.jobs_loop.run_until_complete(asyncio.gather(
*[self.slow_process(*args) for _ in range(count)],
loop=self.jobs_loop,
return_exceptions=True
))
return results
runner = Runner()
print(runner.batch_run(10))
调用batch_run
时,它将调度count
作业并阻塞直到完成。
但是,这在运行中的事件循环引发中不起作用
RuntimeError: Cannot run the event loop while another loop is running
从现有事件循环(例如Jupyter Console)调用batch_run
以及从事件循环外部调用时,如何使def batch_run(self, count, *args):
loop = asyncio.get_event_loop()
jobs = asyncio.gather(...)
if not loop.is_running():
return loop.run_until_complete(jobs)
else:
future = asyncio.ensure_future(jobs, loop=loop)
# loop.wait_until_completed(future)
return future.result()
工作。
编辑
理想情况下,该功能看起来像这样
loop.wait_until_completed
如果只有long time1 = System.currentTimeMillis();
usingStringConcatenation(100000);
System.out.println("usingStringConcatenation " + (System.currentTimeMillis() - time1) + " ms");
time1 = System.currentTimeMillis();
usingStringBuilder(100000);
System.out.println("usingStringBuilder " + (System.currentTimeMillis() - time1) + " ms");
private static void usingStringBuilder(int n)
{
StringBuilder str = new StringBuilder();
for(int i=0;i<n;i++)
str.append("myBigString");
}
private static void usingStringConcatenation(int n)
{
String str = "";
for(int i=0;i<n;i++)
str+="myBigString";
}
存在。