1

I want to read a file line by line and output each line at a fixed interval .

The purpose of the script is to replay some GPS log files whilst updating the time/date fields as the software I'm testing rejects messages if they are too far out from the system time.

I'm attempting to use apscheduler for this as I wanted the output rate to be as close to 10Hz as reasonably possible and this didn't seem achievable with simple sleep commands.

I'm new to Python so I can get a little stuck on the scope of variables with tasks like this. The closest I've come to making this work is by just reading lines from the file object in my scheduled function.

import sys, os
from apscheduler.schedulers.blocking import BlockingScheduler

def emitRMC():
    line = route.readline()
    if line == b'':
        route.seek(0)
        line = route.readline()
    print(line)    


if __name__ == '__main__':

   route = open("testfile.txt", "rb")
   scheduler = BlockingScheduler()
   scheduler.add_executor('processpool')
   scheduler.add_job(emitRMC, 'interval', seconds=0.1)
   scheduler.start()

However this doesn't really feel like the correct way of proceeding and I'm also seeing each input line being repeated 10 times at the output which I can't explain.

The repetition seemed very consistent and I thought it might be due max_workers although I've since set that to 1 without any impact.

I also changed the interval as 10Hz and the 10x repetition felt like it could be something more than a coincidence.

Usually when I get stuck like this it means I'm heading off in the wrong direction and I need pointing to a smarter approach so all advice will be welcome.

1 Answers1

1

I found a simple solution here Executing periodic actions in Python [duplicate] with this code from Micheal Anderson which works in a single thread.

import datetime, threading, time

def foo():
    next_call = time.time()
    while True:
        print datetime.datetime.now()
        next_call = next_call+1;
        time.sleep(next_call - time.time())

timerThread = threading.Thread(target=foo)
timerThread.start()