HyperDevil
HyperDevil

Reputation: 2639

Python time counter

I have data coming in from an outside source (serial port in this case) roughly every 2.5 seconds.
I want to store ( in mysql) a sample of this data every 5 minutes, not every 2.5 seconds.
How would i implement this in python?
One can probably not use a sleep function since this will stop the rest of the script.

Upvotes: 0

Views: 15108

Answers (2)

sotapme
sotapme

Reputation: 4903

Just use the Timer class from threading - something like.

import time
from threading import Timer

def poll_port():
    print "Getting my data from port", time.time()

def main():
    print "Main:enter", time.time()
    while True:
        t = Timer(5, poll_port)
        t.start()
        t.join()
        print "after join:", time.time()

if __name__ == "__main__":
    main()

Example output:

Main:enter 1359755186.87
Getting my data from port 1359755191.88
after join: 1359755191.88
Getting my data from port 1359755196.88
after join: 1359755196.88
Getting my data from port 1359755201.88
after join: 1359755201.88
Getting my data from port 1359755206.88

Upvotes: 1

Nisan.H
Nisan.H

Reputation: 6352

Check how much time has passed since the last save for each incoming event, and update the last-save timestamp after each save:

import time
lastsave = 0
def SaveEvent(data):
    # do what you need to save it
    ...


# I'm assuming there's some sort of event loop that 
# detects new events and directs them to some HandleEvent function

def HandleEvent(data):
    global lastsave
    if time.time() - lastsave > 300: 
    # this is in seconds, so 5 minutes = 300 seconds
        lastsave = time.time()
        SaveEvent(data)

If your application is multithreaded or multiprocessing you should also look into implementing a lock in the SaveEvent function to avoid concurrent saves.

Upvotes: 1

Related Questions