在我的不和谐机器人上同时运行两个循环

时间:2021-03-14 01:45:57

标签: python discord.py bots python-asyncio

所以我在 python 中的 discord bot 的任务是在用户发送消息“$start”后立即发送嵌入。在此之后,代码开始一个 while 循环并检查用户是否做出了反应。同时我想每秒编辑一次机器人的消息,这样我就可以显示某种计时器来向用户显示他们还剩下多少时间做出反应,但我不知道如何实现同时运行的计时器。对这个使用 ```public class ReadJSON { public static void main(String[] args) { //JSON parser object to parse read file JSONParser jsonParser = new JSONParser(); try (FileReader reader = new FileReader("covid19.json")) { //Read JSON file Object obj = jsonParser.parse(reader); JSONArray countryList = (JSONArray) obj; System.out.println(countryList); //Iterate over student array countryList.forEach( std -> parseCOVIDObject( (JSONObject) std ) ); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } } private static void parseCOVIDObject(JSONObject country) { JSONObject CountryObject = (JSONObject)country.get(""); String Country = (String) CountryObject.get("Country"); System.out.println(Country); String Date = (String) CountryObject.get("Date"); System.out.println(Date); String Confirmed = (String) CountryObject.get("Confirmed"); System.out.println(Confirmed); String Deaths = (String) CountryObject.get("Deaths"); System.out.println(Deaths); String Recovered = (String) CountryObject.get("Recovered"); System.out.println(Recovered); } }``` 有用吗? 如果有人需要它来回答我的问题,这是我非常具体的代码:)

multiprocessing

1 个答案:

答案 0 :(得分:2)

我们可以使用 asyncio.gather 并发运行协程。

#after command
from datetime import datetime, timedelta

end_time = datetime.now() + timedelta(seconds=30) #30 seconds to react

async def coro():
   for i in range(30, 0, 5):
       await botMsg.edit(f'time remaining: {i}') #send another message if you don't want old content to be erased
       await asyncio.sleep(5)

async def coro2():
   while datetime.now() <= endtime:
      #do stuff

await asyncio.gather(coro(), coro2())

注意:两个协程的完成之间可能会有一点延迟。

参考文献:

编辑:这是我提到的小延迟Open In Colab

相关问题