线程循环,停止然后每隔x分钟或秒重新启动该功能

时间:2018-01-17 10:07:17

标签: python-2.7 sockets python-multithreading

我有我简化的代码,如下:

def my_function():
    threading.Timer(10.0, my_function).start() # 10 second the function re-runs

    # A TCP socket function

my_function()

虽然这有效,并且每10秒重新启动一次,但套接字仍保持打开状态,因此我收到错误,由于套接字打开等原因无法提取数据。

有没有办法确保套接字在函数结束时关闭?因此,每次重启功能都会重新打开。

完整的功能代码如下。

def iothub_client_sample_run():
threading.Timer(10.0, iothub_client_sample_run).start() # 10 is seconds - change stop to start
try:
    client = iothub_client_init()

    if client.protocol == IoTHubTransportProvider.MQTT:
        print ( "IoTHubClient is reporting state" )
        reported_state = "{\"newState\":\"standBy\"}"
        client.send_reported_state(reported_state, len(reported_state), send_reported_state_callback, SEND_REPORTED_STATE_CONTEXT)




    telemetry.send_telemetry_data(parse_iot_hub_name(), EVENT_SUCCESS, "IoT hub connection is established")

    while True:

        global MESSAGE_COUNT,MESSAGE_SWITCH

        if MESSAGE_SWITCH:

            # send a few messages every minute
            print ( "IoTHubClient sending %d messages" % MESSAGE_COUNT )

            while True:

                try:

                    ip = 'xxxx'
                    port = 'xxxx'

                    conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                    conn.connect((ip,port))

                    print 'connecting...'

                    while True:

                        try:
                            ready_to_read, ready_to_write, in_error = \
                                select.select([conn,], [conn,],[], 5)
                        except:
                            pass

                            print 'connection error'
                            break

                        if len(ready_to_read) > 0:

                            recv2 = conn.recv(2048)

                            try:

                                recv3 = recv2.split(',')

                                date = float(recv3[2])

                                time = float(recv3[3])

                                heave= float(recv3[4])

                                north= float(recv3[5])

                                east = float(recv3[6])


                                msg_txt_formatted = MSG_TXT % (date,time,heave,north,east)





                                try:              
                                    print (msg_txt_formatted)
                                    message = IoTHubMessage(msg_txt_formatted)
                                    # optional: assign ids
                                    message.message_id = "message_%d" % MESSAGE_COUNT
                                    message.correlation_id = "correlation_%d" % MESSAGE_COUNT
                                    # optional: assign properties
                                    prop_map = message.properties()
                                    #prop_map.add("temperatureAlert", "true" if temperature > TEMPERATURE_ALERT else "false")

                                    client.send_event_async(message, send_confirmation_callback, MESSAGE_COUNT)



                                    print ( "IoTHubClient.send_event_async accepted message [%d] for transmission to IoT Hub." % MESSAGE_COUNT )


                                    status = client.get_send_status()

                                    print ( "Send status: %s" % status )
                                    MESSAGE_COUNT += 1
                                    time.sleep(config.MESSAGE_TIMESPAN / 4000.0)


                                except IoTHubError as iothub_error:
                                    print ( "Unexpected error %s from IoTHub" % iothub_error )
                                    telemetry.send_telemetry_data(parse_iot_hub_name(), EVENT_FAILED, "Unexpected error %s from IoTHub" % iothub_error)
                                    return


                            except:
                                print sys.exc_info()[0]

                except:
                    print 're-connecting'


except KeyboardInterrupt:
    print ( "IoTHubClient sample stopped" )


iothub_client_sample_run()

0 个答案:

没有答案