【问题标题】:Kill application at a fixed time在固定时间杀死应用程序
【发布时间】:2015-06-04 02:23:59
【问题描述】:

我正在使用 PyQt4 开发应用程序。我想在一天中的固定时间(比如晚上 11 点)终止这个应用程序。在终止应用程序之前,我想保存一些东西。我正在做的事情如下:

def main():
    app = PyQt4.QtGui.QApplication(sys.argv)
    form = MainWindow()
    form.show()
    app.exec_()

这里MainWindow定义如下:

class MainWindow(PyQt4.QtGui.QMainWindow):
    ...

我不知道该怎么做。有人能指出我正确的方向(或者可能提供代码 sn-p)吗?

【问题讨论】:

    标签: python timer pyqt4 terminate


    【解决方案1】:

    您可以检查当前时间是否已超过预定时间(您无法真正检查时间是否相等)并让您的MainWindow 自行关闭:

    if datetime.datetime.now().time() > datetime.time(hour = 23):
        self.close()
    

    然后通过重载closeEvent 来拦截关闭事件并在那里进行保存:

    def closeEvent(self, event):
        # do some stuff
        event.accept()
    

    【讨论】:

      【解决方案2】:

      您可以使用单次定时器在固定时间调用主窗口的close()槽,然后使用closeEvent保存数据。

      必须注意确保计时器没有给出负值或零间隔。如果应用程序在晚上 12 点开始并设置在晚上 11 点(即第二天)结束,则可能会发生这种情况。

      这是一个简单的演示脚本:

      from PyQt4 import QtCore, QtGui
      
      class MainWindow(QtGui.QMainWindow):
          def __init__(self):
              super(MainWindow, self).__init__()
              time = QtCore.QTime(23, 0, 0)
              now = QtCore.QDateTime.currentDateTime()
              then = QtCore.QDateTime(now.date(), time)
              if now.time() > then.time():
                  then = then.addDays(1)
              print('started at: %s' % now.toString())
              msec = now.msecsTo(then)
              if msec > 0:
                  print('finishing at: %s' % then.toString())
                  QtCore.QTimer.singleShot(msec, self.close)
      
          def closeEvent(self, event):
              print('saving at: %s' % QtCore.QDateTime.currentDateTime().toString())
              # if saving failed, you could prevent closure
              # by calling event.ignore() here
      
      if __name__ == '__main__':
      
          import sys
          app = QtGui.QApplication(sys.argv)
          window = MainWindow()
          window.setGeometry(50, 50, 200, 200)
          window.show()
          sys.exit(app.exec_())
      

      【讨论】:

        猜你喜欢
        • 2020-10-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-09-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-23
        相关资源
        最近更新 更多