本文整理汇总了Python中asyncio.create_task方法的典型用法代码示例。如果您正苦于以下问题:Python asyncio.create_task方法的具体用法?Python asyncio.create_task怎么用?Python asyncio.create_task使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类asyncio
的用法示例。
在下文中一共展示了asyncio.create_task方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import create_task [as 别名]
def __init__(self, bot: Bot):
super().__init__()
self.bot = bot
# Categories
self.available_category: discord.CategoryChannel = None
self.in_use_category: discord.CategoryChannel = None
self.dormant_category: discord.CategoryChannel = None
# Queues
self.channel_queue: asyncio.Queue[discord.TextChannel] = None
self.name_queue: t.Deque[str] = None
self.name_positions = self.get_names()
self.last_notification: t.Optional[datetime] = None
# Asyncio stuff
self.queue_tasks: t.List[asyncio.Task] = []
self.ready = asyncio.Event()
self.on_message_lock = asyncio.Lock()
self.init_task = self.bot.loop.create_task(self.init_cog())
示例2: test_wait_before_create
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import create_task [as 别名]
def test_wait_before_create(zk, path):
"""await barrier.wait() should finish immediately if the barrier does not
exist. Because it is semantically right: No barrier, no blocking.
"""
wait_finished = False
async def start_worker():
barrier = zk.recipes.Barrier(path)
await barrier.wait()
nonlocal wait_finished
wait_finished = True
task = asyncio.create_task(start_worker())
try:
await asyncio.wait_for(task, timeout=2)
except asyncio.TimeoutError:
pass
assert wait_finished
示例3: test_increment_lock
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import create_task [as 别名]
def test_increment_lock(self):
"""Test that we can't produce a race condition in .increment."""
await self.cog.redis.set("test_key", 0)
tasks = []
# Increment this a lot in different tasks
for _ in range(100):
task = asyncio.create_task(
self.cog.redis.increment("test_key", 1)
)
tasks.append(task)
await asyncio.gather(*tasks)
# Confirm that the value has been incremented the exact right number of times.
value = await self.cog.redis.get("test_key")
self.assertEqual(value, 100)
示例4: ensure_valid_reminder
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import create_task [as 别名]
def ensure_valid_reminder(
self,
reminder: dict,
cancel_task: bool = True
) -> t.Tuple[bool, discord.User, discord.TextChannel]:
"""Ensure reminder author and channel can be fetched otherwise delete the reminder."""
user = self.bot.get_user(reminder['author'])
channel = self.bot.get_channel(reminder['channel_id'])
is_valid = True
if not user or not channel:
is_valid = False
log.info(
f"Reminder {reminder['id']} invalid: "
f"User {reminder['author']}={user}, Channel {reminder['channel_id']}={channel}."
)
asyncio.create_task(self._delete_reminder(reminder['id'], cancel_task))
return is_valid, user, channel
示例5: schedule_task
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import create_task [as 别名]
def schedule_task(self, task_id: t.Hashable, task_data: t.Any) -> None:
"""
Schedules a task.
`task_data` is passed to the `Scheduler._scheduled_task()` coroutine.
"""
log.trace(f"{self.cog_name}: scheduling task #{task_id}...")
if task_id in self._scheduled_tasks:
log.debug(
f"{self.cog_name}: did not schedule task #{task_id}; task was already scheduled."
)
return
task = asyncio.create_task(self._scheduled_task(task_data))
task.add_done_callback(partial(self._task_done_callback, task_id))
self._scheduled_tasks[task_id] = task
log.debug(f"{self.cog_name}: scheduled task #{task_id} {id(task)}.")
示例6: init
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import create_task [as 别名]
def init(app: web.Application) -> None:
event_dispatcher = app['event_dispatcher']
event_dispatcher.consume('kernel_preparing', app, handle_kernel_lifecycle)
event_dispatcher.consume('kernel_pulling', app, handle_kernel_lifecycle)
event_dispatcher.consume('kernel_creating', app, handle_kernel_lifecycle)
event_dispatcher.consume('kernel_started', app, handle_kernel_lifecycle)
event_dispatcher.consume('kernel_terminating', app, handle_kernel_lifecycle)
event_dispatcher.consume('kernel_terminated', app, handle_kernel_lifecycle)
event_dispatcher.consume('kernel_success', app, handle_batch_result)
event_dispatcher.consume('kernel_failure', app, handle_batch_result)
event_dispatcher.consume('kernel_stat_sync', app, handle_kernel_stat_sync)
event_dispatcher.consume('kernel_log', app, handle_kernel_log)
event_dispatcher.consume('instance_started', app, handle_instance_lifecycle)
event_dispatcher.consume('instance_terminated', app, handle_instance_lifecycle)
event_dispatcher.consume('instance_heartbeat', app, handle_instance_heartbeat)
event_dispatcher.consume('instance_stats', app, handle_instance_stats)
app['pending_waits'] = set()
# Scan ALIVE agents
app['agent_lost_checker'] = aiotools.create_timer(
functools.partial(check_agent_lost, app), 1.0)
app['stats_task'] = asyncio.create_task(stats_report_timer(app))
示例7: test_election_early_wait_for_leadership
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import create_task [as 别名]
def test_election_early_wait_for_leadership(zk, path):
elec = zk.recipes.LeaderElection(path)
early_wait_success = asyncio.Event()
async def wait_early():
await elec.wait_for_leadership()
assert elec.has_leadership
early_wait_success.set()
asyncio.create_task(wait_early())
await asyncio.sleep(0.5)
assert not elec.has_leadership
await elec.volunteer()
# NO WAIT
await asyncio.wait_for(early_wait_success.wait(), timeout=0.5)
await elec.resign()
assert not elec.has_leadership
await zk.delete(path)
示例8: __init__
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import create_task [as 别名]
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.label = lv.label(self)
self._text = "Text"
self.label.set_long_mode(lv.label.LONG.BREAK)
self.label.set_align(lv.label.ALIGN.CENTER)
self.note = lv.label(self)
style = lv.style_t()
lv.style_copy(style, qr_style)
style.text.font = lv.font_roboto_16
style.text.color = lv.color_hex(0x192432)
self.note.set_style(0, style)
self.note.set_text("")
self.note.set_align(lv.label.ALIGN.CENTER)
self.set_text(self._text)
self.task = asyncio.create_task(self.animate())
self.set_event_cb(self.cb)
示例9: start
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import create_task [as 别名]
def start(self) -> None:
"""(async) Start the PT executable and wait until it's ready.
"Ready" means that all transports have finished initializing.
"""
self._check_not_started()
await self._pre_start()
env = self._build_env()
self._logger.debug('PT environment variables: %r', env)
self._process = await asyncio.create_subprocess_exec(
*self._pt_args,
env=env,
stdin=asyncio.subprocess.PIPE,
stdout=asyncio.subprocess.PIPE,
stderr=None,
)
self._logger.debug('Started PT subprocess: %r', self._process)
self._stdout_task = asyncio.create_task(self._process_stdout())
try:
await self._ready
except Exception:
await self.stop()
raise
示例10: stop
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import create_task [as 别名]
def stop(self):
try:
srv = self._http_proto_server
if srv is not None:
self._http_proto_server = None
srv.close()
await srv.wait_closed()
finally:
try:
async with taskgroup.TaskGroup() as g:
for cmp in self._compilers_list:
g.create_task(cmp.close())
self._compilers_list.clear()
for pgcon in self._pgcons_list:
pgcon.terminate()
self._pgcons_list.clear()
if self._http_request_logger is not None:
self._http_request_logger.cancel()
await self._http_request_logger
finally:
await super().stop()
示例11: asyncTaskAutoCancel
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import create_task [as 别名]
def asyncTaskAutoCancel(func):
"""Wraps an async method into a regular method, that will schedule
the async function as a task. If this task has previously been scheduled
and has not yet run, it will be cancelled. So a newly scheduled task
overrides an older one.
"""
taskAttributeName = f"_{func.__name__}_autoCancelTask"
@functools.wraps(func)
def createFuncTask(self, *args, **kwargs):
oldTask = getattr(self, taskAttributeName, None)
if oldTask is not None:
oldTask.cancel()
coro = func(self, *args, **kwargs)
task = asyncio.create_task(coro)
task.add_done_callback(_done_callback)
setattr(self, taskAttributeName, task)
return task
return createFuncTask
示例12: __init__
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import create_task [as 别名]
def __init__(self, update_statuses):
self._update_statuses = update_statuses
self._process_provider = ProcessProvider()
self._process = None
self._exe = self._find_exe()
self._games_provider = LocalGames()
self.database_parser = None
self.config_parser = ConfigParser(None)
self.uninstaller = None
self.installed_games_cache = self.get_installed_games()
loop = asyncio.get_event_loop()
loop.create_task(self._register_local_data_watcher())
loop.create_task(self._register_classic_games_updater())
self.classic_games_parsing_task = None
示例13: _run
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import create_task [as 别名]
def _run(self):
self._stopping.clear()
self._redis = await utils.create_aredis_for_stream()
self._stream_selector = StreamSelector(self.worker_count, self._redis)
if "stream" in self.enabled_services:
for i in range(self.worker_count):
self._worker_tasks.append(
asyncio.create_task(self.stream_worker_task(i))
)
if "stream-monitoring" in self.enabled_services:
self._stream_monitoring_task = asyncio.create_task(self.monitoring_task())
if "smart-queue" in self.enabled_services:
self._smart_queue_task = asyncio.create_task(
self.smart_queue_processing_task()
)
LOG.debug("%d workers spawned", self.worker_count)
示例14: test_create_task_without_context
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import create_task [as 别名]
def test_create_task_without_context(self):
async def run_later(msg="Hello"):
# print("run_later: %s" % async_tracer.active_span.operation_name)
async with aiohttp.ClientSession() as session:
return await self.fetch(session, testenv["wsgi_server"] + "/")
async def test():
with async_tracer.start_active_span('test'):
asyncio.create_task(run_later("Hello"))
await asyncio.sleep(0.5)
self.loop.run_until_complete(test())
spans = self.recorder.queued_spans()
self.assertEqual(2, len(spans))
self.assertEqual("sdk", spans[0].n)
self.assertEqual("wsgi", spans[1].n)
# Without the context propagated, we should get two separate traces
self.assertNotEqual(spans[0].t, spans[1].t)
示例15: restart_MQTT
# 需要导入模块: import asyncio [as 别名]
# 或者: from asyncio import create_task [as 别名]
def restart_MQTT(self):
if not (bumper.mqtt_server.broker.transitions.state == "stopped" or bumper.mqtt_server.broker.transitions.state == "not_started"):
# close session writers - this was required so bots would reconnect properly after restarting
for sess in list(bumper.mqtt_server.broker._sessions):
sessobj = bumper.mqtt_server.broker._sessions[sess][1]
if sessobj.session.transitions.state == "connected":
await sessobj.writer.close()
#await bumper.mqtt_server.broker.shutdown()
aloop = asyncio.get_event_loop()
aloop.call_later(
0.1, lambda: asyncio.create_task(bumper.mqtt_server.broker.shutdown())
) # In .1 seconds shutdown broker
aloop = asyncio.get_event_loop()
aloop.call_later(
1.5, lambda: asyncio.create_task(bumper.mqtt_server.broker_coro())
) # In 1.5 seconds start broker