Reputation: 11
My requirement is to gather data on my device every 5th minute. This resembles a function app which is triggered every 5th minute. My device has limited resources, and i wish to do this with Python.
I have tried something similar to this, which sleeps until clock is a multiple of 5.
from azure.iot.device.aio import IoTHubModuleClient
from azure.iot.device import Message
from six.moves import input
import asyncio
from datetime import datetime, timedelta
async def main():
sample_interval = 5
executionTime = datetime.utcnow()
try:
nextSample = executionTime + timedelta(minutes=5)
secondsUntilSampleInterval = (nextSample - datetime.utcnow()).seconds
while True:
print("module is connected: " + str(module_client.connected))
if not module_client.connected:
await module_client.connect()
await asyncio.gather(asyncio.sleep(secondsUntilSampleInterval), GatherData())
secondsUntilSampleInterval = sample_interval*60
except Exception as e:
print("Unexpected error %s " % e)
raise
However this does not meet my demands as it drifts over time.
I wish to have the GatherData function triggered when the clock is 10:00, 10:05, 10:10, ...
EDIT: I forgot to mention that the GatherData function is async.
Upvotes: 1
Views: 111
Reputation: 1301
We can use threading..
Import threading and use Timer function in executing our function for every 5 sec. Below is my test sample:
import threading
def runfor5sec():
threading.Timer(5.0, runfor5sec).start() #5 is sec, convert 5 min into sec and replace.
print("Completed 5 Sec")
runfor5sec()
In your case GatherData()
threading.Timer(5.0, GatherData).start() #5 is sec, convert 5 min into sec and
Output:
Upvotes: 0