Using asyncio to run a function at the start (00 seconds) of every minute(使用Asyncio在每分钟开始(00秒)时运行函数)
本文介绍了使用Asyncio在每分钟开始(00秒)时运行函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用不同的参数同时运行多个函数(大约或过程),并在每分钟开始时重复此操作。
我设法让asyncio示例运行,其中我让函数callback使用不同的参数在特定时间运行,但我不知道如何在非常特定的时间运行它(并永远运行它)(即我想在每分钟开始时运行它,因此在19:00:00、19:01:00等等)。
Asynciocall_at应该能够做到这一点,但它使用的时间格式不是标准的Python时间格式,我无法将该时间格式指定为下一分钟的00秒。
import asyncio
import time
def callback(n, loop, msg):
print(msg)
print('callback {} invoked at {}'.format(n, loop.time()))
async def main(loop):
now = loop.time()
print('clock time: {}'.format(time.time()))
print('loop time: {}'.format(now))
print('registering callbacks')
loop.call_at(now + 0.2, callback, 1, loop, 'a')
loop.call_at(now + 0.1, callback, 2, loop, 'b')
loop.call_soon(callback, 3, loop, 'c')
await asyncio.sleep(1)
event_loop = asyncio.get_event_loop()
try:
print('entering event loop')
event_loop.run_until_complete(main(event_loop))
finally:
print('closing event loop')
event_loop.close()
Python
正如一些评论员所说,在纯推荐答案中仅使用异步CIO并不容易做到这一点,但是使用apScheduler库实际上就变得相当容易了。
import asyncio
import datetime
import os
from apscheduler.schedulers.asyncio import AsyncIOScheduler
def tick():
print("Tick! The time is: %s" % datetime.datetime.now())
if __name__ == "__main__":
scheduler = AsyncIOScheduler()
scheduler.add_job(tick, "cron", minute="*")
scheduler.start()
print("Press Ctrl+{0} to exit".format("Break" if os.name == "nt" else "C"))
# Execution will block here until Ctrl+C (Ctrl+Break on Windows) is pressed.
try:
asyncio.get_event_loop().run_forever()
except (KeyboardInterrupt, SystemExit):
pass
这篇关于使用Asyncio在每分钟开始(00秒)时运行函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:使用Asyncio在每分钟开始(00秒)时运行函数
基础教程推荐
猜你喜欢
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- 包装空间模型 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- 求两个直方图的卷积 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
