我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用asyncio.sleep()。
def waitFor(self, selectorOrFunctionOrTimeout: Union[str, int, float], options: dict = None, **kwargs: Any) -> Awaitable: """Wait until `selectorOrFunctionOrTimeout`.""" if options is None: options = dict() options.update(kwargs) if isinstance(selectorOrFunctionOrTimeout, (int, float)): fut: Awaitable[None] = asyncio.ensure_future( asyncio.sleep(selectorOrFunctionOrTimeout)) return fut if not isinstance(selectorOrFunctionOrTimeout, str): fut = asyncio.get_event_loop().create_future() fut.set_exception(TypeError( 'Unsupported target type: ' + str(type(selectorOrFunctionOrTimeout)) )) return fut if ('=>' in selectorOrFunctionOrTimeout or selectorOrFunctionOrTimeout.strip().startswith('function')): return self.waitForFunction(selectorOrFunctionOrTimeout, options) return self.waitForSelector(selectorOrFunctionOrTimeout, options)
def play(self, ctx, voice_channel: discord.Channel=None): """Play Radio Haru""" server = ctx.message.server author = ctx.message.author if voice_channel == None: voice_channel = author.voice_channel if self.voice_connected(server): await self.bot.say("Already connected to a voice channel, use `{}radioharu stop` to change radio.".format(ctx.prefix)) else: try: voice = await self.bot.join_voice_channel(voice_channel) Channel = ctx.message.channel await self.bot.send_typing(Channel) player = voice.create_ffmpeg_player('https://cdn.discordapp.com/attachments/336598653923753987/360413654224601089/Radio-Haru.ogg', use_avconv=self.use_avconv) player.start() await asyncio.sleep(7) player.stop() player = voice.create_ffmpeg_player('https://stream.radioharu.pw/radioharu', use_avconv=self.use_avconv) player.start() await self.bot.say(":green_heart: **Playing Radio Haru!**") except InvalidArgument: await self.bot.say("You either didn't enter a voice channel to connect to, or weren't in one!")
def smart_delay(delay: float, last_cmd: float, remain: int=0) -> float: """ A "smart" delay mechanism which tries to reduce the delay as much as possible based on the time the last delay happened. :param delay: delay in seconds :param last_cmd: time of last command :param remain: counter, skip delay unless it's zero :return: timestamp to feed to next invocation """ now = time.monotonic() if remain == 0 and last_cmd is not None and delay > 0.0: delta = now - last_cmd if delta < delay: sleep = delay - delta time.sleep(sleep) return now
def send_loop(self): while True: await asyncio.sleep(0.25) if len(self.send_queue) == 0: continue # Copy send queue and clear the global one queue = self.send_queue.copy() self.send_queue.clear() # Process and push out the queue. try: await self.instance.gbx.multicall(*queue) except Fault as e: if 'Login unknown' in str(e): return logger.exception(e) handle_exception(exception=e, module_name=__name__, func_name='send_loop') except Exception as e: logger.exception(e) handle_exception(exception=e, module_name=__name__, func_name='send_loop')
def check(self): """ Check the database health. """ try: if isinstance(self.migrator, MySQLMigrator): cursor = self.db.engine.execute_sql( 'SELECT DEFAULT_COLLATION_NAME FROM information_schema.SCHEMATA WHERE SCHEMA_NAME LIKE %s;', self.db.engine.database ) result = cursor.fetchone() if len(result) == 1: if result[0] != 'utf8mb4_unicode_ci': logger.error( 'Your database, tables and column collate is \'{}\' and it should be \'utf8mb4_unicode_ci\'! ' 'Please change your database collate right now!'.format(result[0]) ) logger.warning( 'Please read the information on this page on how to convert your collate: ' 'http://www.pypla.net/en/stable/howto/dbcollate.html' ) logger.info('Wait 5 seconds to ignore!... (We strongly advice to change it!)') await asyncio.sleep(5) except: pass # Totally ignore.
def get_player(self, login=None, pk=None, lock=True): """ Get player by login or primary key. :param login: Login. :param pk: Primary Key identifier. :param lock: Lock for a sec when receiving. :return: Player or exception if not found :rtype: pyplanet.apps.core.maniaplanet.models.Player """ try: if login: return await Player.get_by_login(login) elif pk: return await Player.get(pk=pk) else: raise PlayerNotFound('Player not found.') except DoesNotExist: if lock: await asyncio.sleep(4) return await self.get_player(login=login, pk=pk, lock=False) else: raise PlayerNotFound('Player not found.')
def __getattr__(self, name): """ Wrap method calls in coroutines that use run_in_executor to make them async. """ attr = getattr(self._cs, name) if not callable(attr): wrapper = partial(getattr, self._cs, name) setattr(self, name, wrapper) else: async def coro(*args, **kwargs): method = partial(attr, *args, **kwargs) for attempt in range(1, 4): try: return await self.loop.run_in_executor(None, method) except theblues.errors.ServerError: if attempt == 3: raise await asyncio.sleep(1, loop=self.loop) setattr(self, name, coro) wrapper = coro return wrapper
def model_uuids(self): """Return a mapping of model names to UUIDs. """ controller_facade = client.ControllerFacade.from_connection( self.connection()) for attempt in (1, 2, 3): try: response = await controller_facade.AllModels() return {um.model.name: um.model.uuid for um in response.user_models} except errors.JujuAPIError as e: # retry concurrency error until resolved in Juju # see: https://bugs.launchpad.net/juju/+bug/1721786 if 'has been removed' not in e.message or attempt == 3: raise await asyncio.sleep(attempt, loop=self._connector.loop)
def _reconnect(self): while True: try: if self._halted: yield from asyncio.sleep(2, loop=self._loop) else: self.log.info('Connecting to PLM on %s', self.device) yield from serial.aio.create_serial_connection( self._loop, lambda: self.protocol, self.device, baudrate=19200) self._reset_retry_interval() return except OSError: self._increase_retry_interval() interval = self._get_retry_interval() self.log.warning('Connecting failed, retry in %i seconds: %s', interval, self.device) yield from asyncio.sleep(interval, loop=self._loop)
def steal(self, ctx, user: discord.Member=None): """Steal cookies from another user. 2h cooldown.""" author = ctx.message.author server = author.server action = "Steal CD" settings = self.check_server_settings(author.server) self.account_check(settings, author) if user is None: user = self.random_user(settings, author, server) if user == "Fail": pass elif user.bot: return await self.bot.say("Stealing failed because the picked target is a bot.\nYou " "can retry stealing again, your cooldown is not consumed.") if await self.check_cooldowns(author.id, action, settings): msg = self.steal_logic(settings, user, author) await self.bot.say("?(=(|) ? (|)=)? Neko-chan is on the prowl to steal :cookie:") await asyncio.sleep(4) await self.bot.say(msg)
def _end_lottery(self, ctx): """Manually ends a lottery. Use help on end lottery for more info This command must be used on an active lottery that does not have a timer set or you will be unable to start a new lottery. This command may also be used to end a lottery which has a timer, early using this command. """ author = ctx.message.author settings = self.check_server_settings(author.server) if not settings["Config"]["Active"]: return await self.bot.say("I can't end a lottery that hasn't even begun.") loadout = settings["Config"]["Current Loadout"] load_pref = settings["Loadouts"][loadout] end_msg = self.lottery_teardown(settings, load_pref, author.server) await self.bot.say("The lottery is now ending...") await asyncio.sleep(5) await self.bot.say(end_msg)
def end(self, ctx): """Ends a raffle""" if self.raffle["Config"]["Active"]: if len(self.raffle["Players"]) > 0: self.raffle["Config"]["Active"] = False tickets = self.raffle["Config"]["Tickets"] winning_ticket = random.choice(tickets) winner = [] for subdict in self.raffle["Players"]: if winning_ticket in self.raffle["Players"][subdict]["Tickets"]: winner.append(subdict) mention = "<@" + winner[0] + ">" await self.bot.say("The winner of the raffle is...") await asyncio.sleep(3) await self.bot.say(mention + "! Congratulations, you have won!") self.raffle["Config"]["Tickets"] = [] self.raffle["Players"] = {} else: self.raffle["Config"]["Active"] = False await self.bot.say("Oh no! No one joined the raffle. Cancelling the raffle.") dataIO.save_json(self.file_path, self.raffle) else: await self.bot.say("You need to start a raffle for me to end one!")
def vault_updater(self): await self.bot.wait_until_ready() try: await asyncio.sleep(20) # Start-up Time while True: servers = [x.id for x in self.bot.servers if x.id in self.system["Servers"]] for server in servers: for target in self.system["Servers"][server]["Targets"]: vault = self.system["Servers"][server]["Targets"][target]["Vault"] vault_max = self.system["Servers"][server]["Targets"][target]["Vault Max"] if vault < vault_max: increment = min(vault + int(vault_max * 0.04), vault_max) self.system["Servers"][server]["Targets"][target]["Vault"] = increment else: pass self.save_system() await asyncio.sleep(120) # task runs every 120 seconds except asyncio.CancelledError: pass
def heist_game(self, settings, server, t_heist, t_crew, t_vault): crew = len(settings["Crew"]) target = self.heist_target(settings, crew) settings["Config"]["Heist Start"] = True players = [server.get_member(x) for x in settings["Crew"]] results = self.game_outcomes(settings, players, target) start_output = self.message_handler(settings, crew, players) await self.bot.say("Get ready! The {} is starting with {}\nThe {} has decided to " "hit **{}**.".format(t_heist, start_output, t_crew, target)) await asyncio.sleep(3) await self.show_results(settings, results) if settings["Crew"]: players = [server.get_member(x) for x in settings["Crew"]] data = self.calculate_credits(settings, players, target) headers = ["Players", "Credits Obtained", "Bonuses", "Total"] t = tabulate(data, headers=headers) msg = ("The credits collected from the {} was split among the winners:\n```" "C\n{}```".format(t_vault, t)) else: msg = "No one made it out safe." settings["Config"]["Alert Time"] = int(time.perf_counter()) self.reset_heist(settings) self.save_system() await self.bot.say(msg)
def test_delete_with_rule_cascade(self): try: class SomeRef(Document): pass class SomeDoc(Document): ref = ReferenceField( SomeRef, reverse_delete_rule=mongoengine.CASCADE) r = SomeRef() yield from r.save() d = SomeDoc(ref=r) yield from d.save() yield from r.delete() yield from asyncio.sleep(0.05) with self.assertRaises(SomeDoc.DoesNotExist): yield from SomeDoc.objects.get(id=d.id) finally: yield from SomeRef.drop_collection() yield from SomeDoc.drop_collection()
def test_delete_with_rule_nullify(self): try: class SomeRef(Document): pass class SomeDoc(Document): ref = ReferenceField( SomeRef, reverse_delete_rule=mongoengine.NULLIFY) r = SomeRef() yield from r.save() d = SomeDoc(ref=r) yield from d.save() yield from r.delete() yield from asyncio.sleep(0.01) d = yield from SomeDoc.objects.get(id=d.id) self.assertIsNone((yield from d.ref)) finally: yield from SomeRef.drop_collection() yield from SomeDoc.drop_collection()
def test_delete_with_rule_pull(self): try: class SomeRef(Document): pass class SomeDoc(Document): ref = ListField(ReferenceField( SomeRef, reverse_delete_rule=mongoengine.PULL)) r = SomeRef() yield from r.save() d = SomeDoc(ref=[r]) yield from d.save() yield from r.delete() yield from asyncio.sleep(0.01) d = yield from SomeDoc.objects.get(id=d.id) self.assertEqual(len((yield from d.ref)), 0) finally: yield from SomeRef.drop_collection() yield from SomeDoc.drop_collection()
def _api_call(self, method, **params): url = "{0}/bot{1}/{2}".format(API_URL, self.api_token, method) logger.debug("api_call %s, %s", method, params) response = await self.session.post(url, data=params) if response.status == 200: return await response.json() elif response.status in RETRY_CODES: logger.info("Server returned %d, retrying in %d sec.", response.status, RETRY_TIMEOUT) await response.release() await asyncio.sleep(RETRY_TIMEOUT) return await self.api_call(method, **params) else: if response.headers['content-type'] == 'application/json': err_msg = (await response.json())["description"] else: err_msg = await response.read() logger.error(err_msg) raise RuntimeError(err_msg)
def ping_handler(self): ping_interval = self.shark.config['WS_PING']['interval'] if not ping_interval: return latency = 0 while True: await asyncio.sleep(ping_interval - latency) self.session.log.debug('ping') start_time = time.time() try: ping = await self.websocket.ping() except websockets.ConnectionClosed: return timeout_handler = asyncio.ensure_future( self.ping_timeout_handler(ping)) await ping latency = time.time() - start_time self.session.log.debug('pong', latency=round(latency, 3)) # Return immediately if a ping timeout occurred. if not timeout_handler.cancel() and timeout_handler.result(): return
def reaction_time(self, ctx): '''Reaction time game''' response, embed = await self.bot.say("Please choose 10 reactions") while len(response.reactions) < 10: await self.bot.wait_for_reaction(message = response) response = await self.bot.get_message(ctx.message.channel, response.id) reactions = response.reactions reaction = random.choice(reactions) await self.bot.edit_message(response, "Please wait..") for _reaction in reactions: try: await self.bot.add_reaction(response, _reaction.emoji) except discord.errors.HTTPException: await self.bot.edit_message(response, ":no_entry: Error: Please don't deselect your reactions before I've selected them") return for countdown in range(10, 0, -1): await self.bot.edit_message(response, "First to select the reaction _ wins.\nMake sure to have all the reactions deselected.\nGet ready! {}".format(countdown)) await asyncio.sleep(1) await self.bot.edit_message(response, "First to select the reaction {} wins. Go!".format(reaction.emoji)) start_time = timeit.default_timer() winner = await self.bot.wait_for_reaction(message = response, emoji = reaction.emoji) elapsed = timeit.default_timer() - start_time await self.bot.edit_message(response, "{} was the first to select {} and won with a time of {:.5} seconds!".format(winner.user.display_name, reaction.emoji, elapsed))
def delete_number(self, ctx, number, check, delete_command = True): if number <= 0: await self.bot.embed_reply(":no_entry: Syntax error") return to_delete = [] count = 0 if delete_command: await self.bot.attempt_delete_message(ctx.message) async for message in self.bot.logs_from(ctx.message.channel, limit = clients.delete_limit): if check(message): to_delete.append(message) count += 1 if count == number: break elif len(to_delete) == 100: await self.bot.delete_messages(to_delete) to_delete.clear() await asyncio.sleep(1) if len(to_delete) == 1: await self.bot.attempt_delete_message(to_delete[0]) elif len(to_delete) > 1: await self.bot.delete_messages(to_delete)
def websitescreenshot(self, url : str): '''Take a screenshot of a website''' response, embed = None, None while True: async with clients.aiohttp_session.get("http://api.page2images.com/restfullink?" "p2i_url={}&p2i_screen=1280x1024&p2i_size=1280x0&p2i_fullpage=1&p2i_key={}".format(url, credentials.page2images_api_key)) as resp: data = await resp.json() if data["status"] == "processing": wait_time = int(data["estimated_need_time"]) if response and embed: embed.description = "Processing {}\nEstimated wait time: {} sec".format(url, wait_time) await self.bot.edit_message(response, embed = embed) else: response, embed = await self.bot.embed_reply("Processing {}\nEstimated wait time: {} sec".format(url, wait_time)) await asyncio.sleep(wait_time) elif data["status"] == "finished": await self.bot.embed_reply("Your screenshot of {}:".format(url), image_url = data["image_url"]) return elif data["status"] == "error": await self.bot.embed_reply(":no_entry: Error: {}".format(data["msg"])) return
def play_library(self, requester, timestamp): if not self.not_interrupted.is_set(): return False if not self.library_flag: await self.bot.embed_say(":notes: Playing songs from my library") self.library_flag = True try: self.pause() except errors.AudioError: paused = False else: paused = True self.not_interrupted.clear() while self.bot.is_voice_connected(self.server) and self.library_flag: await self.play_from_library("", requester, timestamp, clear_flag = False) await asyncio.sleep(0.1) # wait to check self.not_interrupted.set() if paused: self.resume() return True
def checkRemind(self, member, reminder): # Start our countdown countDown = int(reminder['End'])-int(time.time()) if countDown > 0: # We have a positive countdown - let's wait await asyncio.sleep(countDown) # Check if member is online - if so - remind them if not str(member.status).lower() == "offline": # Well, they're not Offline... reminders = self.settings.getUserStat(member, member.server, "Reminders") # Verify reminder is still valid if not reminder in reminders: return server = reminder['Server'] message = reminder['Message'] if not message: message = 'You wanted me to remind you of something...' msg = 'In *{}*, you wanted me to remind you:\n\n{}'.format(server, message) await self.bot.send_message(member, msg) reminders.remove(reminder) self.settings.setUserStat(member, member.server, "Reminders", reminders)
def getHungry(self): while not self.bot.is_closed: # Add The Hunger await asyncio.sleep(900) # runs every 15 minutes for server in self.bot.servers: # Iterate through the servers and add them isKill = self.settings.getServerStat(server, "Killed") if isKill.lower() == "no": hunger = int(self.settings.getServerStat(server, "Hunger")) # Check if hunger is 100% and increase by 1 if not hunger += 1 if hunger > 100: hunger = 100 self.settings.setServerStat(server, "Hunger", hunger)
def test_poll(mocker, SETTINGS, WORKERS): SETTINGS.REPOSITORIES = 'owner/repo' mocker.patch('jenkins_epo.procedures.WORKERS', WORKERS) whoami = mocker.patch('jenkins_epo.procedures.whoami', CoroutineMock()) asyncio = mocker.patch('jenkins_epo.procedures.asyncio') asyncio.sleep = CoroutineMock() WORKERS.queue.join.side_effect = [None, ValueError()] from jenkins_epo.procedures import poll with pytest.raises(ValueError): yield from poll() assert whoami.mock_calls assert asyncio.sleep.mock_calls assert WORKERS.queue.join.mock_calls
def test_throttle_sleep(mocker, SETTINGS): GITHUB = mocker.patch('jenkins_epo.procedures.GITHUB') GITHUB.rate_limit.aget = CoroutineMock(return_value=dict()) compute_throttling = mocker.patch( 'jenkins_epo.procedures.compute_throttling' ) sleep = mocker.patch( 'jenkins_epo.procedures.asyncio.sleep', CoroutineMock(name='sleep'), ) from jenkins_epo.procedures import throttle_github compute_throttling.return_value = 100 yield from throttle_github() assert sleep.mock_calls
def setUp(self): this = self class SessionMock: response = ObjectWrapper(ResponseMock(0.1)) async def request(self, *args, **kwargs): await sleep(this.spend_time) self.response._post_init(this.loop) return self.response self.plugin = Elapsed() self.session = ObjectWrapper(SessionMock()) self.endpoint_desc = {'path': '/test1/path/noway', 'method': 'GET', 'param1': 'obladi', 'param2': 'oblada'} self.request_params = {'path_param1': 'foo', 'path_param2': 'bar'}
def test_limit(self): await self.plugin.before_request(self.endpoint_desc, self.session, self.request_params) fut = asyncio.ensure_future(self.plugin.before_request(self.endpoint_desc, self.session, self.request_params)) with self.assertRaises(TimeoutError): await asyncio.wait_for(shield(fut), 0.1) await self.plugin.on_response(self.endpoint_desc, self.session, self.request_params, None) await asyncio.sleep(0.2) await asyncio.wait_for(fut, 0.5)
def connection_runtime(self): connection_data = [] i2 = 0 for i in self.rtobj.rtobj_get(): if i[0] in self.servers[0] or i[0] in self.servers[1]: connection_data.append([i[0], i[1]]) if len(connection_data) == 2: break i2 += 1 connection_data[0][1].new_connection(self, self.servers[1][1], 0, self.servers[1][2]) connection_data[1][1].new_connection(self, self.servers[0][1], 1, self.servers[0][2]) while True: if len(self.incoming) != 0: connection_data[self.incoming[0][1]][1].connection_receive(self.incoming[0]) self.incoming.pop(0) if self.closed: break await asyncio.sleep(.01)
def test_redis_wait_infinite_raises_timeout_exception(event_loop, redis_instance): manager = build_manager(dsn=redis_instance, loop=event_loop) globals()["test_redis_wait_infinite_timeout_raises_finished"] = False @manager.task() async def task_test_redis_wait_oks(): await asyncio.sleep(2, loop=event_loop) return True async def run(): manager.run() with pytest.raises(AioTasksTimeout): async with task_test_redis_wait_oks.delay(infinite_timeout=0.2) as f: pass event_loop.run_until_complete(run()) manager.stop()
def test_redis_delay_task_decorator_timeout_raises(event_loop, redis_instance): manager = build_manager(dsn=redis_instance, loop=event_loop) globals()["test_redis_delay_task_decorator_timeout_raises_finished_tasks"] = False @manager.task() async def task_test_redis_delay_task_decorator_timeout_raises(num): await asyncio.sleep(num, loop=event_loop) globals()["test_redis_delay_task_decorator_timeout_raises_finished_tasks"] = True async def run(): manager.run() await task_test_redis_delay_task_decorator_timeout_raises.delay(1) await manager.wait(timeout=0.2, exit_on_finish=True, wait_timeout=0.1) event_loop.run_until_complete(run()) manager.stop() assert globals()["test_redis_delay_task_decorator_timeout_raises_finished_tasks"] is False del globals()["test_redis_delay_task_decorator_timeout_raises_finished_tasks"]
def test_redis_subscribers_timeout_raises(event_loop, redis_instance): manager = build_manager(dsn=redis_instance, loop=event_loop) globals()["test_redis_subscribers_timeout_raises_finished_tasks"] = False @manager.subscribe("hello") async def task_test_redis_subscribers_oks(topic, data): if topic == "hello": await asyncio.sleep(data, loop=event_loop) globals()["test_redis_subscribers_timeout_raises_finished_tasks"] = True async def run(): manager.run() await manager.publish("hello", 5) await manager.wait(timeout=0.5, exit_on_finish=True, wait_timeout=0.1) event_loop.run_until_complete(run()) manager.stop() assert globals()["test_redis_subscribers_timeout_raises_finished_tasks"] is False del globals()["test_redis_subscribers_timeout_raises_finished_tasks"]
def test_memory_wait_infinite_raises_timeout_exception(event_loop): manager = build_manager(dsn="memory://", loop=event_loop) globals()["test_memory_wait_infinite_timeout_raises_finished"] = False @manager.task() async def task_test_memory_wait_oks(): await asyncio.sleep(2, loop=event_loop) return True async def run(): manager.run() with pytest.raises(AioTasksTimeout): async with task_test_memory_wait_oks.delay(infinite_timeout=0.2) as f: pass event_loop.run_until_complete(run()) manager.stop()
def test_memory_delay_task_decorator_timeout_raises(event_loop): manager = build_manager(dsn="memory://", loop=event_loop) globals()["test_memory_delay_task_decorator_timeout_raises_finished_tasks"] = False @manager.task() async def task_test_memory_delay_task_decorator_timeout_raises(num): await asyncio.sleep(num, loop=event_loop) globals()["test_memory_delay_task_decorator_timeout_raises_finished_tasks"] = True async def run(): manager.run() await task_test_memory_delay_task_decorator_timeout_raises.delay(1) await manager.wait(timeout=0.2, exit_on_finish=True, wait_timeout=0.1) event_loop.run_until_complete(run()) manager.stop() assert globals()["test_memory_delay_task_decorator_timeout_raises_finished_tasks"] is False del globals()["test_memory_delay_task_decorator_timeout_raises_finished_tasks"]
def test_memory_subscribers_timeout_raises(event_loop): manager = build_manager(dsn="memory://", loop=event_loop) globals()["test_memory_subscribers_timeout_raises_finished_tasks"] = False @manager.subscribe("hello") async def task_test_memory_subscribers_oks(topic, data): if topic == "hello": await asyncio.sleep(data, loop=event_loop) globals()["test_memory_subscribers_timeout_raises_finished_tasks"] = True async def run(): manager.run() await manager.publish("hello", 5) await manager.wait(timeout=0.5, exit_on_finish=True, wait_timeout=0.1) event_loop.run_until_complete(run()) manager.stop() assert globals()["test_memory_subscribers_timeout_raises_finished_tasks"] is False del globals()["test_memory_subscribers_timeout_raises_finished_tasks"]
def hello(): print('hello world') r = await asyncio.sleep(1) print('hello again') # ??EventLoop:
def __refresh_info_call(self): while True: await asyncio.sleep(60) await self.refresh_info()
def vote_reminder(self, vote): await asyncio.sleep(await self.setting_remind_interval.get_value()) if self.current_vote is not None: required_votes = (self.current_vote.votes_required - len(self.current_vote.votes_current)) current_required_votes = (vote.votes_required - len(vote.votes_current)) if self.current_vote.action == vote.action and current_required_votes == required_votes: message = '$0cfThere are $fff{}$0cf more {} needed to $fff{}$0cf (use $fffF5$0cf to vote).'.format( current_required_votes, ('votes' if current_required_votes > 1 else 'vote'), self.current_vote.action ) await self.instance.chat(message) asyncio.ensure_future(self.vote_reminder(vote))
def server_update_loop(self): while True: await asyncio.sleep(5) try: if self.update_pending: await self.server_widget.display() self.update_pending = False except: pass
def on_after_start(self, *args, **kwargs): await asyncio.sleep(1) asyncio.ensure_future(asyncio.gather(*[ self.player_connect(p) for p in self.instance.player_manager.online ]))
def map_start(self, *args, **kwargs): await asyncio.sleep(2) await self.widget.display()
def loop(self): while True: await asyncio.sleep(60*5) try: await self.capture('online_ping', dict( total_players=self.instance.player_manager.count_all, )) except: pass
def recv(self): if not self.responses: await asyncio.sleep(1) # delay to give test time to finish raise ConnectionClosed(0, 'ran out of responses') return json.dumps(self.responses.popleft())
def test_monitor_catches_error(event_loop): async with base.CleanModel() as model: conn = model.connection() assert conn.monitor.status == 'connected' try: async with conn.monitor.reconnecting: await conn.ws.close() await asyncio.sleep(1) assert conn.monitor.status == 'error' finally: await conn.close()
def test_reconnect(event_loop): async with base.CleanModel() as model: kwargs = model.connection().connect_params() conn = await Connection.connect(**kwargs) try: await asyncio.sleep(0.1) assert conn.is_open await conn.ws.close() assert not conn.is_open await model.block_until(lambda: conn.is_open, timeout=3) finally: await conn.close()
def _wait_for_model_gone(controller, model_name): while model_name in await controller.list_models(): await asyncio.sleep(0.5, loop=controller.loop)
def block_until(*conditions, timeout=None, wait_period=0.5, loop=None): """Return only after all conditions are true. """ async def _block(): while not all(c() for c in conditions): await asyncio.sleep(wait_period, loop=loop) await asyncio.wait_for(_block(), timeout, loop=loop)
def main(self, bundle): """Main entry point for task creation with an asyncio event loop. The number of concurrent requests is throttled using this async method. Depending on the download strategy used, the method will call the request_and_download async method or immediately return the bundle indicating that the file came from cache as the file existed. :param bundle: bundle (generally one that has just been instantiated) :type bundle: :class:`aiodownload.AioDownloadBundle` :return: bundle with updated properties reflecting it's final state :rtype bundle: :class:`aiodownload.AioDownloadBundle` """ with (await self._main_semaphore): bundle.file_path = self._download_strategy.get_file_path(bundle) file_exists = os.path.isfile(bundle.file_path) if not (file_exists and self._download_strategy.skip_cached): while bundle._status_msg in (STATUS_ATTEMPT, STATUS_INIT, ): if bundle._status_msg == STATUS_ATTEMPT: logger.info(bundle.status_msg) sleep_time = self._request_strategy.get_sleep_time(bundle) logger.debug('Sleeping {} seconds between requests'.format(sleep_time)) await asyncio.sleep(sleep_time) bundle = await self.request_and_download(bundle) else: bundle._status_msg = STATUS_CACHE logger.info(bundle.status_msg) return bundle