简体   繁体   中英

Python threading with connection as connect in loop

I cant start 2 separated threads on 1 connection to server. I want run 2 functions in loop, it looks like they are executed one by one. Are there any other option to run functions every x seconds/min?

Threading is good tool to use?

import time
import datetime
from threading import Thread

def func1(ts3conn):
    print(f"func 1, pause 2sec NOW:{datetime.datetime.now()}")
    time.sleep(2)

def func2(ts3conn):
    print(f"func2, pause 10sec NOW:{datetime.datetime.now()}")
    time.sleep(10)

if __name__ == "__main__":

    with ts3.query.TS3ServerConnection("telnet://serveradmin:passwod@1.2.3.4:10011") as ts3conn:
        ts3conn.exec_("use", sid=1)
        ts3conn.exec_("clientupdate", client_nickname="BOT")
        while True:
            Thread(target=func1(ts3conn)).start()
            Thread(target=func2(ts3conn)).start()

func 1, pause 2sec NOW:2019-08-24 23:53:19.139951
func2, pause 10sec NOW:2019-08-24 23:53:21.141273
func 1, pause 2sec NOW:2019-08-24 23:53:31.141770
func2, pause 10sec NOW:2019-08-24 23:53:33.142568
func 1, pause 2sec NOW:2019-08-24 23:53:43.143090
func2, pause 10sec NOW:2019-08-24 23:53:45.143880

The target parameter expects a callable (ie function), but you're passing the result of calling that callable and the sleep is occurring before the thread is even created.

So instead of this:

Thread(target=func1(ts3conn)).start()

... try something like this:

Thread(target=func1, args=(ts3conn,)).start()

Unfortunately when you fix this issue you're going have another problem: the while loop is not going to wait for the threads to finish before creating new threads, and will continue creating new threads until the application crashes. You may want to try something like this:

while True:
    t1 = Thread(target=func1, args=(ts3conn,))
    t2 = Thread(target=func2, args=(ts3conn,))
    t1.start()
    t2.start()

    # wait for the threads to finish
    t1.join()
    t2.join()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM