在 Python 3 中安排重复事件 [英] Schedule a repeating event in Python 3

查看:62
本文介绍了在 Python 3 中安排重复事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试安排一个重复事件在 Python 3 中每分钟运行一次.

I'm trying to schedule a repeating event to run every minute in Python 3.

我见过 sched.scheduler 类,但我想知道是否还有其他方法可以做到.我听说我可以为此使用多个线程,我不介意这样做.

I've seen class sched.scheduler but I'm wondering if there's another way to do it. I've heard mentions I could use multiple threads for this, which I wouldn't mind doing.

我基本上是请求一些 JSON 然后解析它;它的价值随着时间的推移而变化.

I'm basically requesting some JSON and then parsing it; its value changes over time.

要使用 sched.scheduler 我必须创建一个循环来请求它安排偶数运行一小时:

To use sched.scheduler I have to create a loop to request it to schedule the even to run for one hour:

scheduler = sched.scheduler(time.time, time.sleep)

# Schedule the event. THIS IS UGLY!
for i in range(60):
    scheduler.enter(3600 * i, 1, query_rate_limit, ())

scheduler.run()

还有什么其他方法可以做到这一点?

What other ways to do this are there?

推荐答案

你可以使用 threading.Timer,但它也调度一次性事件,类似于调度器对象的 .enter 方法.

将一次性调度器转换为周期性调度器的正常模式(在任何语言中)是让每个事件在指定的时间间隔内重新调度自身.例如,对于 sched,我不会像您那样使用循环,而是使用类似:

The normal pattern (in any language) to transform a one-off scheduler into a periodic scheduler is to have each event re-schedule itself at the specified interval. For example, with sched, I would not use a loop like you're doing, but rather something like:

def periodic(scheduler, interval, action, actionargs=()):
    scheduler.enter(interval, 1, periodic,
                    (scheduler, interval, action, actionargs))
    action(*actionargs)

并通过调用启动整个永久定期计划"

and initiate the whole "forever periodic schedule" with a call

periodic(scheduler, 3600, query_rate_limit)

或者,我可以使用 threading.Timer 而不是 scheduler.enter,但模式非常相似.

Or, I could use threading.Timer instead of scheduler.enter, but the pattern's quite similar.

如果您需要更精细的变化(例如,在给定时间或特定条件下停止定期重新安排),使用一些额外参数并不太难.

If you need a more refined variation (e.g., stop the periodic rescheduling at a given time or upon certain conditions), that's not too hard to accomodate with a few extra parameters.

这篇关于在 Python 3 中安排重复事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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