2

I would like to ask is it possible to get the system clock interrupt in Python for each second, so that I do not need to constantly check the clock in loop?

1

If you want to go a bit more abstract, timing and event drive programming is what the Twisted python framework is about.

An example of a function acting every second would be:

from twisted.internet import task
from twisted.internet import reactor

def runEverySecond():
    print "a second has passed"

l = task.LoopingCall(runEverySecond)
l.start(1.0) # call every second

# l.stop() will stop the looping calls
reactor.run()

This code comes straight from one of the twisted task scheduling examples.

What is particularly cool about this framework is that its completely asleep (no CPU) between the times it wakes up (waking up from timers and events are all handled in the kernal via epoll() or select() not inside the python).

I've been using Twisted heavily for my Rasp Pi dev and I'm quite taken by its ability to handle complex event tasks with very little CPU. Be warned thought that once you get beyond simple tasks it becomes complex fast (... though I would argue complex in a good way).

If you want very comprehensive (and fairly easy to follow) deep dive into it, look at krondo's Twisted Introduction

(BTW Twisted isn't a default framework on raspbian, you need to load it, and to do that you need the python C dev stuff loaded too, so a sudo apt-get install python-dev, sudo apt-get install build-essential followed by a pip install twisted (there is an apt-get for twisted too (python-twisted) but is really old, so I would recommend pip'ing it instead))

| improve this answer | |
0

signal.settimer() seems like what you're looking for. please, tell us if for some reason this won't work for you, we'll dig deeper.

| improve this answer | |
  • I think this might fit better as a comment, unless the OP tells us that he used that and that it worked. Seeing as it is a suggestion, and not a very in-depth answer. – RPiAwesomeness Apr 13 '14 at 18:48
  • @RPiAwesomeness a comment cannot be accepted as an answer – lenik Apr 14 '14 at 12:32
  • I know that. However, the way you worded this made me think that this would fit better as a comment. You could have commented it, and then, if the OP decided that this worked, created an answer. It's just my opinion though. – RPiAwesomeness Apr 14 '14 at 15:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.