【问题标题】:Keep one method constantly running and another method executing every certain period保持一种方法不断运行,另一种方法每隔一段时间执行一次
【发布时间】:2016-12-03 15:03:49
【问题描述】:

所以目前我是这两种方法,一种是不断从另一台设备读取射频数据,另一种是每隔一段时间发送一次数据。

我怎么能这样做?我需要不断更新和接收传入的 RF 数据,而 sendData() 方法只是尽可能从全局变量中获取数据。

下面的代码到目前为止,但它不工作......

import httplib, urllib
import time, sys
import serial
from multiprocessing import Process

key = 'MY API KEY'
rfWaterLevelVal = 0

ser = serial.Serial('/dev/ttyUSB0',9600)

def rfWaterLevel():
    global rfWaterLevelVal

    rfDataArray = ser.readline().strip().split()
    print 'incoming: %s' %rfDataArray
    if len(rfDataArray) == 5:
        rfWaterLevelVal = float(rfDataArray[4])
        print 'RFWater Level1: %.3f cm' % (rfWaterLevelVal)
        #rfWaterLevel = 0

def sendData():
    global rfWaterLevelVal

    params = urllib.urlencode({'field1':rfWaterLevelVal, 'key':key})
    headers = {"Content-type" : "application/x-www-form-urlencoded","Accept": "text/plain"}
    conn = httplib.HTTPConnection("api.thingspeak.com:80", timeout = 5)
    conn.request("POST", "/update", params, headers)
    #print 'RFWater Level2: %.3f cm' % (rfWaterLevelVal)
    response = conn.getresponse()
    print response.status, response.reason
    data = response.read()
    conn.close()

while True:
    try:
        rfWaterLevel()
        p = Process(target=sendData(), args())
        p.start()
        p.join()

        #Also tried threading...did not work..
        #t1 = threading.Thread(target=rfWaterLevel())
        #t2 = threading.Thread(target=sendData())
        #t1.start()
        #t1.join()
        #t2.join()
    except KeyboardInterrupt:
        print "caught keyboard interrupt"
        sys.exit()

请帮忙!

澄清一下,我需要 rfWaterLevel() 方法不断运行,因为 rf 数据不断传入,并且我需要 sendData() 在它准备好再次发送后立即被调用(大约每 5 秒左右) .但似乎,如果传入的射频数据有任何延迟,那么射频数据就会停止自我更新(接收端),因此发送的数据与射频发射器发送的数据不准确。

提前致谢!

【问题讨论】:

    标签: python multithreading multiprocessing raspberry-pi2


    【解决方案1】:

    我不能给你一个完整的解决方案,但我可以引导你走向正确的方向。

    您的代码存在三个问题。

    1. Process 启动(顾名思义)一个新进程而不是一个新线程。 新进程不能与旧进程共享数据。 您应该改用多线程。 看看threading 解释here

    2. 您正在主线程内调用rfWaterLevel()。 进入while循环前需要启动第二个线程。

    3. 您在 while 循环中一次又一次地创建第二个线程。 只创建一次并将while循环放在函数内

    你的基本程序结构应该是这样的:

    import time
    
    def thread_function_1():
        while True:
            rfWaterLevel()
    
    def thread_function_2():
        while True:
            sendData()
            time.sleep(5)
    
    # start thread 1
    thread1 = Thread(target = thread_function_1)
    thread1.start()
    
    # start thread 2
    thread2 = Thread(target = thread_function_2)
    thread2.start()
    
    # wait for both threads to finish
    thread1.join()
    thread2.join()
    

    【讨论】:

    • 感谢您的回答,只是一个问题,如果第一个线程不是“应该”停止的怎么办?所以我的意思是,第一个线程函数应该随着 rf 数据不断进入而不断运行......我是否只是摆脱了两者的“join()”语句?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-25
    • 2011-10-06
    • 2018-10-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多