Python Forum

Full Version: Better Way to Monitor Time Request.
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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.')
I would try to use the builtin sched module for this.
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.