Real-time interrupts in Python

后端 未结 2 1194
盖世英雄少女心
盖世英雄少女心 2020-12-16 22:05

I have a Python 2.7 program running an infinite while loop and I want to incorporate a timer interrupt. What I aim to do is to set off a timer at some point in the loop, and

相关标签:
2条回答
  • 2020-12-16 22:26

    You can't get real-time without special hardware/software support. You don't need it in most cases (do you need to control giant robots?).

    How to delay several function calls by known numbers of seconds depends on your needs e.g., if a time it takes to run a function is negligible compared to the delay between the calls then you could run all functions in a single thread:

    #!/usr/bin/env python
    from __future__ import print_function
    from Tkinter import Tk
    
    root = Tk()
    root.withdraw() # don't show the GUI window
    root.after(1000, print, 'foo') # print foo in a second
    root.after(0, print, 'bar') # print bar in a jiffy
    root.after(2000, root.destroy) # exit mainloop in 2 seconds
    root.mainloop()
    print("done")
    

    It implements yours "I do not want the interrupts to interrupt each other either" because the next callback is not called until the previous one is complete.

    0 讨论(0)
  • 2020-12-16 22:33

    If a single event is to be handled, then the easiest way is to use the signal framework which is a standard module of Python.

    However, if we need a fully-fledged scheduler, then we have to resort to another module: sched. Here is a pointer to the official documentation. Please be aware, though, that in multi-threaded environments sched has limitations with respect to thread-safety.

    Another option is the Advanced Python Scheduler, which is not part of the standard distribution.

    0 讨论(0)
提交回复
热议问题