如何将python paho-mqtt与作业队列集成?

问题描述 投票:1回答:2

我正在编写需要使用Python并订阅某些主题的IoT项目应用程序。收到消息后,我需要将新作业以及相应的优先级添加到队列中,然后将根据该优先级执行该作业。问题是有时有时可能同时有很多消息,因此我需要确定它们的优先级,并在先前完成时执行它们。

问题是我无法将两者都集成。我正在使用

的队列示例
import Queue

class Job(object):
    def __init__(self, priority, description):
        self.priority = priority
        self.description = description
        print 'New job:', description
        return
    def __cmp__(self, other):
        return cmp(self.priority, other.priority)

q = Queue.PriorityQueue()

q.put( Job(3, 'Mid-level job') )
q.put( Job(10, 'Low-level job') )
q.put( Job(1, 'Important job') )

while not q.empty():
    next_job = q.get()
    print 'Processing job:', next_job.description

问题是放在底部的位置

while not q.empty():
        next_job = q.get()
        print 'Processing job:', next_job.description

内部MQTT-paho结构

我有这个

import paho.mqtt.client as mqtt
import datetime
import json
from time import sleep

import Queue

class Job(object):
    def __init__(self, priority, description):
        self.priority = priority
        self.description = description
        print 'New job:', description
        return
    def __cmp__(self, other):
        return cmp(self.priority, other.priority)

q = Queue.PriorityQueue()

from pprint import pprint

def on_connect(client, userdata, flags, rc): 
    client.subscribe("mytopic")

def on_message(client, userdata, msg):
    #here I had the job to queqe for example
    q.put( Job(1, 'Important job') )

#where should I call the queue

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message

client.connect("host", 1883, 60)

client.loop_forever()

我尝试将其添加到on_message,但出现此错误

File "myfile.py", line 136, in <module>
    client.loop_forever()
python paho
2个回答
2
投票

尝试使用:client.loop_start()代替client.loop_forever()


0
投票

尝试使用另一个线程来处理client.loop_forever()

© www.soinside.com 2019 - 2024. All rights reserved.