Search code examples
pythonmultithreadingqtpyqtqapplication

python QApplication freezes and does not close while another thread is running


In the main file i run a Qapplication in the main thread (that starts with no problem) and a method on a separate thread , called backupGiornaliero. When I try to close the application via the X button of the user interface of the app or by a button that should close the application (associated with the method sys.exit(app.exec_())) the application freezes or simply doesn't end.

This is my main without all the imports:


def backupGiornaliero():

    dataOggi=datetime.today().strftime('%Y-%m-%d')
    orarioBackup = " 22:00:00"
    dataOrarioBackup = str(dataOggi+orarioBackup)
    datatimeBackup = datetime.strptime(dataOrarioBackup, '%Y-%m-%d %H:%M:%S')

    if datetime.now() < datatimeBackup:
        unixDataBackup = time.mktime(datatimeBackup.timetuple())
    else:
        unixDataBackup = time.mktime(datatimeBackup.timetuple())+ float(86400)

    print("unix timestamp dell'orario di backup di oggi "+str(unixDataBackup))

    # Set up scheduler
    s = sched.scheduler(time.time, time.sleep)
    # Schedule when you want the action to occur
    s.enterabs(unixDataBackup, 0, BackupModel().eseguiBackup)
    # Block until the action has been run
    s.run()

    print("fatto backup")


# Press the green button in the gutter to run the script.
if __name__ == '__main__':

    x = threading.Thread(target=backupGiornaliero)
    x.start()

    app = QApplication(sys.argv)
    vistaLogin = LoginView(app)
    vistaLogin.show()
    sys.exit(app.exec())
    

Thanks for the help.


Solution

  • Actually it seems that it's sufficient to set the separate thread as a daemon so that when the main thread ends its work all the deamon threads stop as well. In my case so i solved with x.setDaemon(true)