Random beginner-question: trigger on reaching certain OS-time

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By pferft

Hi everyone,

I’m seraching for a way to have a signal emitted on reaching a certain OS-time…

I have two Labels, an hour-Label and a minute-Label, which contain the numbers the user enters, e. g. “08” and “35”. Perhaps a way could be comparing these numbers to the actual according OS-time numbers (preferably once every second, not necessarily on every frame) and then trigger if they match.

Would that be a good approach? Or is there a better way? (I’d assume this was a popular feature but I couldn’d find any example.)

:bust_in_silhouette: Reply From: magicalogic

You could use OS.get_datetime(). Here’s what the docs say about it:

Dictionary get_datetime ( bool utc=false ) const

Returns current datetime as a dictionary of keys: year, month, day, weekday, dst (Daylight Savings Time), hour, minute, second.

Then emit your signal when it returns the time you want.

This would be perfect. But how could I tell Godot my time of choice?
I only used OS.get_datetime() for displaying the current year, month, day and time etc. by now.

pferft | 2021-05-19 12:24

:bust_in_silhouette: Reply From: pferft

golddotasksquestions on reddid suggested for “trigger something exactly at a specific OS-time, down to a specific second”:

var alarm_has_not_triggered = true

func _process(delta):
	var time = OS.get_time()
	var time_string = str(str(time.hour).pad_zeros(2),":",str(time.minute).pad_zeros(2),":",str(time.second).pad_zeros(2))
	if time_string == "17:15:30" and alarm_has_not_triggered:
		print("The Time Is Now")
		alarm_has_not_triggered = false

and for “trigger something repeatedly every second, in sync with OS-time-second”:

var last_second = OS.get_time().second

func _process(delta):
	var time = OS.get_time()
	if time.second != last_second:
		print("start of a new second")
	last_second = time.second

which work like a charm.
(I added some “returns” not to have the time printed on each frame.)

Just wanted to add here for the “trigger every second” and this depends on your usecase ofcourse.
If the hour and minute your user can enter is far in the future (like say 10 minutes).
Then it seems wastefull to check every second for the os-time if this time has reached.

You could get the os-time once, do a diff for how long to wait and then create a timer for that amount.
When the timer reaches its end, then you could either do want you need to do or start the “trigger every second” if it really needs to be on the exact os-time.

see the docs here for timer

aipie | 2021-05-19 17:43

This is indeed a very reasonable thought. A “trigger every minute” scenario would seem okay, but “wasteful” is the right word for each second, especially considering that in my case the time-distance can reach several hours. Thanks for the hint, aipie!

pferft | 2021-05-19 18:31