如何在Python与瓶执行周期任务 [英] How to perform periodic task with Flask in Python

查看:99
本文介绍了如何在Python与瓶执行周期任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用为我的 k8055 USB接口板;相当标准的getter和推杆,以及瓶真的让我的生活轻松了许多。

I've been using Flask to provide a simple web API for my k8055 USB interface board; fairly standard getters and putters, and Flask really made my life a lot easier.

不过,我希望能够以注册状态的变化/近乳清时发生。

But I want to be able to register changes of state as / near when whey happen.

举例来说,如果我有连接到电路板上的按钮,我可以查询特定端口的API。但是,如果我想有输出直接反映了产出,是否有人在说的API,我想有这样的事情。

For instance, if I have a button connected to the board, I can poll the api for that particular port. But if I wanted to have the outputs directly reflect the outputs, whether or not someone was talking to the api, I would have something like this.

while True:
    board.read()
    board.digital_outputs = board.digital_inputs
    board.read()
    time.sleep(1)

和每一秒,输出将被更新,以匹配输入。

And every second, the outputs would be updated to match the inputs.

有没有办法做这样的事情瓶下?我已经做过类似的事情在以前扭曲,但瓶是太方便了这个特定的应用程序就可以放弃,只是还没有...

Is there any way to do this kind of thing under Flask? I've done similar things in Twisted before but Flask is too handy for this particular application to give up on it just yet...

感谢。

推荐答案

您可以用cron简单的任务。

You could use cron for simple tasks.

您的任务创建一个烧瓶视图。

Create a flask view for your task.

# a separate view for periodic task
@app.route('/task')
def task():
    board.read()
    board.digital_outputs = board.digital_inputs

然后使用cron的,从网址下载定期

Then using cron, download from that url periodically

# cron task to run each minute
0-59 * * * * run_task.sh

在哪里run_task.sh内容

Where run_task.sh contents are

wget http://localhost/task

cron是不能比每分钟一次更频繁地运行。如果需要更高的频率,(比方说,分别5秒期间=每分钟12次),则必须做到在tun_task.sh通过以下方式

Cron is unable to run more frequently than once a minute. If you need higher frequency, (say, each 5 seconds = 12 times per minute), you must do it in tun_task.sh in the following way

# loop 12 times with a delay
for i in 1 2 3 4 5 6 7 8 9 10 11 12
do
    # download url in background for not to affect delay interval much
    wget -b http://localhost/task
    sleep 5s
done

这篇关于如何在Python与瓶执行周期任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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