AppleScript:如何结束repeatwhile true循环



我有适用于Mac的安非他命应用程序,下面是用AppleScript控制它的官方文档。我有这个脚本,它几乎每5分钟创建一个新的会话,持续5分钟,但也会检查盖子是否打开,如果打开了,它会询问你是否想继续。

问题是,当我将AppleScript保存为.app文件并将其放在dock中时,当我右键单击并选择"时,我无法退出它;退出"我怎样才能做到这一点?我在谷歌上搜索了很多答案,但没有找到任何解决方案。

tell application "Amphetamine" to start new session with options {duration:5, interval:minutes, displaySleepAllowed:false}
repeat while true
tell application "Amphetamine" to start new session with options {duration:5, interval:minutes, displaySleepAllowed:false}
set lid to do shell script "ioreg -r -k AppleClamshellState -d 4 | grep AppleClamshellState"
if lid contains "no" then
set notification to display alert "Keep Mac Awake" message "The lid is opened. Would you like to stop?" buttons ["Continue", "Stop"] default button 2
if button returned of notification is equal to "Stop" then
tell application "Amphetamine" to end session
exit repeat
end if
end if
delay 290
end repeat

这种情况下的最佳解决方案不是使用无限重复循环,而是使用on idle((onquit((理程序来保持应用程序的打开状态。将以下脚本保存为保持打开的应用程序,然后尝试。我无法测试,因为我的Mac上没有安装Amphetamine.app。

on idle {}
tell application "Amphetamine" to start new session with options {duration:5, interval:minutes, displaySleepAllowed:false}
set lid to do shell script "ioreg -r -k AppleClamshellState -d 4 | grep AppleClamshellState"
if lid contains "no" then
tell application "System Events" to set frontProcess to 1st process whose frontmost is true
tell frontProcess to set notification to display alert "Keep Mac Awake" message "The lid is opened. Would you like to stop?" buttons ["Continue", "Stop"] default button 2
if button returned of notification is equal to "Stop" then quit {}
end if
return 290
end idle

on quit {}
tell application "Amphetamine" to end session
continue quit
end quit

最新更新