保持一种方法不断运行,另一种方法每隔一段时间执行一次

Keep one method constantly running and another method executing every certain period

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

我该怎么做?我需要不断更新和接收传入的 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 秒左右)。但似乎,如果输入的 rf 数据有任何延迟,则 rf 数据会停止自身更新(接收端),因此发送的数据与 rf 发射器发送的数据不准确。

提前致谢!

我无法为您提供完整的解决方案,但我可以指导您朝着正确的方向前进。

您的代码存在三个问题。

  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()