Stay-Open watchdog with idle handler v. launchd managed osascript

I wrote 2 scripts to monitor battery level on my aging laptop. 5% warning is too late. The 1st one relies on launchd to schedule every 15 minutes a test. The second one is a stay-open script with idle handler launched when logging-in. I wonder which is the most efficient way to handle the task. How does AppleScript internally take care of scheduling?

For a stay open AppleScript application, that would be with the idle handler. To set the duration between executions you would return an integer which tells AppleScript how long to wait till it runs the idle handler again.

Thanks, Robert, I do have both script working ok. I did set up the idle loop to my needs. I was wondering about efficiency of both solutions. The ā€œon idleā€ handler must somehow have an internal scheduling mechanism of some sort.

My instinct is to say that the stay open AppleScript app with an idle handler would be slightly more effective as it does not have to launch or initialize a new process every time it runs. (Of course if it has to launch or initialize a new process to check the battery, then that would be less efficient).

Yes, at the end of the idle handler put this line
ā€œreturn 20ā€
It will then cause the idle handler to run every 20 seconds

Did some testing.
AppleScript uses launchd to manage ā€œon idleā€ handlers. So the difference must be marginal.

I made this simple code saved as an application (SimpleOnIdleStayOpen.app) with stay open option ticked:

on idle
	tell application "Finder"
		activate
		display alert "Ouch !" giving up after 5
	end tell
	return 30
end idle

In Activity Monitor we can seel the parent process.
Capture dā€™eĢcran 2024-05-13 aĢ€ 13.31.21
in terminal too:
$ launchctl list | grep Simple
3836 0 com.apple.ScriptEditor.id.SimpleOnIdleStayOpen.3004

BTW this simple trick to make a stay-open application faceless still works, on Big Sur, Intel HW.

3 Likes

It very easy to make a faceless background app.

in the Appā€™s info.plist, add these lines

<key>LSBackgroundOnly</key>
<integer>1</integer>

This will make your app run in the background and not show on the dock when run

1 Like

Thanks @jean.o.matic . Itā€™s really helpful.

1 Like