I am writing an application to output a fake MSF signal from a raspberry pi like computer to sync a radio clock with an NTP server. The application is being written in python and I have control over the pin I plan to use for outputting the signal but I need to synchronise the python script with the system clock. I have found how to sleep for relatively accurate periods but I haven't found anything that would allow me to trigger a function at a specified system time (top of the next minute for instance) with a reasonable degree of accuracy (within 100mS or so)
-
Possible duplicate of [In Python, how can I put a thread to sleep until a specific time?](https://stackoverflow.com/questions/2031111/in-python-how-can-i-put-a-thread-to-sleep-until-a-specific-time) – Alastair McCormack Aug 15 '17 at 13:51
-
Or perhaps use https://pypi.python.org/pypi/APScheduler/1.01 – Alastair McCormack Aug 15 '17 at 13:59
1 Answers
As this is an asynchronous call (independent from what the program does in the rest of the time, I would do it using asyncio
's AbstractEventLoop.call_at
It syncs to the system clock. If you get the desired precision depends on the system clock, but on my machine running under Linux, it usually has a precision within some milliseconds (I haven't tested on a Raspberry Pi, though). A simple Python 3 example would look like this:
import asyncio
import datetime
import time
def callback(loop):
print('Hello World!')
loop.stop() # Added to make program terminate after demo
event_loop = asyncio.get_event_loop()
execution_time = datetime.datetime(2017,8,16,13,37).timestamp()
# Adjust system time to loop clock
execution_time_loop = execution_time - (time.time() - event_loop.time())
# Register callback
event_loop.call_at(execution_time_loop, callback, event_loop)
try:
print('Entering event loop')
event_loop.run_forever()
finally:
print('Closing event loop')
event_loop.close()
The example is supposed write 'Hello, World!' on the 16th of August, 2017, at 13:37 UTC. Notice that the time within the event loop is not system time, so you need to express the desired execution time in event loop time. To have the program not stop after execution of the task, remove the loop.stop()
at the end of the callback.

- 199
- 6