Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
427 views
in Technique[技术] by (71.8m points)

applescript - trying to write an apple script that chimes every hour

I'm trying to write this script that chimes on every hour. I saved it as an application and selected the checkbox run after completion but it doesn't work. My code looks like this:

global chime
set chime to (path to resource "chime.mp3")
on idle
    set currenthour to hours of (current date)
    if currenthour = 0 then
        set currenthour to 12
    end if
    if currenthour > 12 then
        set currenthour to currenthour - 12
    end if
    set currentminute to minutes of (current date)
    set currentsecond to seconds of (current date)
    set currenttime to {currentminute, currentsecond} as text
    if currenttime is "" then
        repeat currenthour times
            do shell script "afplay " & (quoted form of POSIX path of chime)
        end repeat
    end if
    return 1
end idle
question from:https://stackoverflow.com/questions/65602858/trying-to-write-an-apple-script-that-chimes-every-hour

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In a script app, the number you return from the on idle handler tells the system how long to sleep the app before the next idle invocation. You can use this set up a (loosely) accurate timer.

global chime, firstRun

on run
    -- I'm not sure if this is necessary, but I always use explicit run handlers in script apps.
    set chime to (path to resource "chime.mp3")
    set firstRun to true
end run

on idle
    set {currenthour, currentminute, currentsecond} to {hours, minutes, seconds} of (current date)
    
    -- don't chime when the script app is activated
    if not firstRun then
        
        -- quick mathy way to retrieve the number of chimes.
        set chimeCount to (currenthour + 11) mod 12 + 1
        repeat chimeCount times
            do shell script "afplay " & (quoted form of POSIX path of chime)
        end repeat
    else
        set firstRun to true
    end if
    
    -- calculate the number of seconds until the next hour mark and tell app to sleep until then
    return 60 * (60 - currentminute) + 60 - currentsecond
end idle

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...