Oneechan69
Oneechan69

Reputation: 198

AppleScript: How can I end a repeat while true loop?

I have the Amphetamine app for Mac and here's the official documentation to control it with AppleScript. I have this script where every almost 5 mins it creates a new session for 5 mins but also checks if the lid is opened, if so, it will ask if you want to continue.

The problem is that when I save the AppleScript as a .app file and put it in my dock, I can't quit it when I right click and select "Quit." How can I make it do so? I did a bunch of googling for answers but I didn't find any solutions.

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

Upvotes: 0

Views: 992

Answers (1)

Robert Kniazidis
Robert Kniazidis

Reputation: 1878

The best solution im this case is not using the infinite repeat loop, but stay-open application with on idle() and on quit() handlers. Save following script as stay-open application, then try it. I can't test because the Amphetamine.app is not installed on my Mac.

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

Upvotes: 1

Related Questions