Python Forum
Better Way to Monitor Time Request. - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: General (https://python-forum.io/forum-1.html)
+--- Forum: Code Review (https://python-forum.io/forum-46.html)
+--- Thread: Better Way to Monitor Time Request. (/thread-30330.html)



Better Way to Monitor Time Request. - bill_z - Oct-16-2020

Being new to Python, but not to programming, I’m concerned with efficiency regarding CPU cycles. My project is to collect data then write it out to a log file every 5 minutes. I want to write nearly exactly every 5 minutes by the clock. I really want it to report on the hour and exactly every 5 minutes after. Python on a Raspberry Pi 3B+

The following sample code does work but I’m betting there is a more efficient way to do this. Us new guys don't know many tricks.

Will someone suggest a better way please?

import time, datetime
from time import sleep

last = 0

try:
	while True:
		date_time = datetime.datetime.now()
		date = date_time.date()  # Gives the date
		time = date_time.time()  # Gives the time
		min = int(time.minute)   # Gives the minute

		if min != last:
			if min in (00,05,10,15,20,25,30,35,40,45,50,55):
				print ("time :",date, time)
				last = min


except KeyboardInterrupt:
    print('You canceled the operation.')



RE: Better Way to Monitor Time Request. - Gribouillis - Oct-16-2020

I would try to use the builtin sched module for this.


RE: Better Way to Monitor Time Request. - ndc85430 - Oct-17-2020

You could also use cron (I'm assuming Raspbian has a cron daemon running by default of course) to run your program at the scheduled times.