Running code in background on Android

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

I would like to make a timer that runs out even if I switch the screen off or use another app once the timer started. Is it possible somehow? thanks guys

I also need the answer to this question.

hashak | 2019-07-19 10:53

same here I need answers as well

Mike Trevor | 2019-08-06 09:49

:bust_in_silhouette: Reply From: Shawk

var wait_time := 3600 # how long the timer should last, in seconds (this example is 1 hour)
var start_time := OS.get_unix_time() # set this value to `OS.get_unix_time() whenever you want to reset the timer

(below would go in _process() or _physics_process())

var time_left := start_time + wait_time - OS.get_unix_time()
if time_left < 0:
	# put code to run when timer ends here

You would probably want to store the start_time value in the disk as well in case the app gets closed by the device to save memory while the user is doing something else
One caveat is that it’s dependant on the device’s time being accurate and that the user isn’t changing it. If the user changes their device’s time, it can trick the app into thinking it actually is whatever time they set it to
Also the timer might run out while the user isn’t using the app so keep that in mind and take that into account when you program whatever happens when it runs out.