0

いくつかの更新を行うスレッドを持つ python Gui アプリケーションがあります。これがその実装方法です。

GObject.threads_init()
Class main:
    #Extra stuff here
    update_thread = Thread(target= update_func, args=(Blah blah,))
    update_thread.setDaemon(True)
    update_thread.start()
    Gtk.main()

これは update_func がどのように見えるかです

def update_func():
    try:
        #do updating
        time.sleep(#6hrs)
    except:
        #catch error 
        time.sleep(#5 min)
    finally:
        update_func()

プログラムが実行されている限り、スレッドは実行され、私が持っているプログラムは何日も実行されます。問題は、スレッドが停止して更新が行われず、アプリケーションを再起動する必要があることです。

特にGuiアプリケーションで、現在のスレッドが終了した場合に新しいスレッドを開始する方法はありますか?

4

1 に答える 1

1

以下は、私の gtk アプリの 1 つから抜粋したスレッドの例です。役に立つかもしれません。

#!/usr/bin/env python3

# Copyright (C) 2013 LiuLang <gsushzhsosgsu@gmail.com>

# Use of this source code is governed by GPLv3 license that can be found
# in http://www.gnu.org/licenses/gpl-3.0.html


from gi.repository import GObject
from gi.repository import Gtk
import threading

#UPDATE_INTERVAL = 6 * 60 * 60 * 1000   # 6 hours
UPDATE_INTERVAL = 2 * 1000   # 2 secs, for test only

def async_call(func, func_done, *args):
    '''
    Call func in another thread, without blocking gtk main loop.

    `func` does time-consuming job in background, like access website.
    If `func_done` is not None, it will be called after func() ends.
    func_done is called in gtk main thread, and this function is often used
    to update GUI widgets in app.
    `args` are parameters for func()
    '''
    def do_call(*args):
        result = None
        error = None

        try:
            result = func(*args)
        except Exception as e:
            error = e

        if func_done is not None:
            GObject.idle_add(lambda: func_done(result, error))

    thread = threading.Thread(target=do_call, args=args)
    thread.start()

class App(Gtk.Window):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.set_default_size(480, 320)
        self.set_border_width(5)
        self.set_title('Gtk Threads')
        self.connect('delete-event', self.on_app_exit)

        self.update_timer = GObject.timeout_add(UPDATE_INTERVAL,
                self.check_update)

    def run(self):
        self.show_all()
        Gtk.main()

    def on_app_exit(self, *args):
        Gtk.main_quit()

    def check_update(self):
        def _do_check_update():
            print('do check update: will check for updating info')
            print(threading.current_thread(), '\n')

        print('check update')
        print(threading.current_thread())
        async_call(_do_check_update, None)
        return True


if __name__ == '__main__':
    app = App()
    app.run()
于 2013-11-09T11:20:15.040 に答える