试图编写一个每小时响起的苹果脚本

trying to write an apple script that chimes every hour

我正在尝试编写每小时响起的脚本。我将其保存为应用程序并在完成后选中了复选框 运行,但它不起作用。我的代码如下所示:

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

在脚本应用程序中,return 来自 on idle 处理程序的数字告诉系统在下一次空闲调用之前应用程序要休眠多长时间。您可以使用它来设置一个(松散的)精确计时器。

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