首页 > 解决方案 > How to have my defined refresh function running in the background of my twisted server

问题描述

I have a simple twisted TCP server running absolutely fine, it basically deals with database requests and displays the right things its just an echo client with a bunch of functions, the database that is being read also updates I have this refresh function to open the database and refresh it however if I add this to the message functions it'll take too long to respond as the refresh function takes around 6/7 seconds to complete, my initial idea was to have this function in a while loop and running constantly refreshing every 5/10 mins but after reading about the global interpreter lock its made me think that that isn't possible, any suggestions on how to run this function in the background of my code would be greatly appreciated

I've tried having it in a thread but it doesn't seem to run at all when I start the thread, I put it under the if name == 'main': function and no luck!

Here is my refresh function

def refreshit()
    Application = win32com.client.Dispatch("Excel.Application")
    Workbook = Application.Workbooks.open(database)
    Workbook.RefreshAll()
    Workbook.Save()
    Application.Quit()
    xlsx = pd.ExcelFile(database)
    global datess
    global refss
    df = pd.read_excel(xlsx, sheet_name='Sheet1')
    datess = df.groupby('documentDate')
    refss = df.groupby('reference')


class Echo(Protocol):
    global Picked_DFS
    Picked_DFS = None
    label = None
    global errors
    global picked
    errors = []
    picked = []
    def dataReceived(self, data):
        """
        As soon as any data is received, write it back.
        """
        response = self.handle_message(data)
        print('responding with this')
        print(response)
        self.transport.write(response)

def main():
    f = Factory()
    f.protocol = Echo
    reactor.listenTCP(8000, f)
    reactor.run()

if __name__ == '__main__':
    main()

I had tried this to no avail

if __name__ == '__main__':
    main()
    thread = Thread(target = refreshit())
    thread.start()
    thread.join()

标签: python-3.xmultithreadingtwistedwin32com

解决方案


您在此行有一个重要错误:

thread = Thread(target = refreshit())

虽然您没有包含refreshit(可能是考虑重命名的函数)的定义,但我假设refreshit是一个执行刷新的函数。

在这种情况下,您在这里所做的是调用 refreshit并等待它返回一个值。然后,它返回的值用作Thread您在此处创建的目标。这可能不是你的意思。反而:

thread = Thread(target = refreshit)

也就是说,refreshit 它本身就是你想要的线程目标。

您还需要确保对操作进行排序,以便所有操作都可以同时运行:

if __name__ == '__main__':
    # Start your worker/background thread.
    thread = Thread(target = refreshit)
    thread.start()
    # Run Twisted
    main()
    # Cleanup/wait on your worker/background thread.
    thread.join()

您可能还只想使用 Twisted 的线程支持而不是直接使用该threading模块(但这不是强制性的)。

if __name__ == '__main__':
    # Start your worker/background thread.
    thread = Thread(target = refreshit)
    thread.start()
    # Run Twisted
    main()
    # Cleanup/wait on your worker/background thread.
    thread.join()

推荐阅读