Home > python > Terminate a script after X seconds

Terminate a script after X seconds

In Qt, there is a class called QTimer. With QTimer you can, for instance, terminate your application in X seconds. Example:

#!/usr/bin/env python

import sys

from PySide.QtCore import *
from PySide.QtGui import *

SEC = 1000    # 1 sec. is 1000 msec.

def main():
    app = QApplication(sys.argv)
    form = QDialog()
    # suicide in 3 seconds:
    QTimer.singleShot(3 * SEC, app.quit)

if __name__ == "__main__":

Question: how to have the same effect in a command-line application?

I came up with the following solution:

#!/usr/bin/env python

import sys
from time import sleep
import signal

class MyTimer(object):
    Similar to Qt's QTimer. Call a function in a specified time.

    Time is given in sec. Usage:
    mt = MyTimer()
    mt.singleShot(<sec>, <function_name>)

    After setting it, you can still disable it:

    If you call it several times, any previously scheduled alarm
    will be canceled (only one alarm can be scheduled at any time).
    def singleShot(self, sec, func):
        self.f = func
        signal.signal(signal.SIGALRM, self.handler)

    def handler(self, *args):

    def disable(self):

def main():
    while True:
        print '.',
if __name__ == "__main__":
    mt = MyTimer()
    mt.singleShot(3, sys.exit)

As can be seen, the main function has an eternal loop. However, this program will terminate in 3 seconds. I’m imitating QTimer’s singleshot. The differences: (1) you must create a MyTimer object, and (2) time is given in seconds, not in milliseconds. You can also write it in one line if you want: MyTimer().singleShot(3, sys.exit).

It is written in a general form, so instead of sys.exit, you can also call a different function.

  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: