使用Asyncio在每分钟开始(00秒)时运行函数 [英] Using asyncio to run a function at the start (00 seconds) of every minute

查看:17
本文介绍了使用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秒)时运行函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆