如何在 OSX 中每天自动运行一个应用程序

How to automate an app to run daily in OSX

我对 AppleScript 编程还很陌生。这是我在下午 6 点打开应用程序的代码。我将此代码保存为应用程序,现在我想在每天下午 6 点自动打开此应用程序,无需任何用户交互。我想以编程方式执行此操作;没有 cron 作业,没有 Automator,没有日历,没有用户偏好设置。我想要代码来触发它。可能吗?

set targetTime to "6:00:00 PM"


display dialog targetTime -- wait until we reach the target date/time
repeat while (current date) is less than date targetTime
    -- should be 60

end repeat


tell application "Myapp"

    activate

end tell

-- get the time in the desired format
on getTimeInHoursAndMinutes()

    -- Get the "hour"
    set timeStr to time string of (current date)
    set Pos to offset of ":" in timeStr
    set theHour to characters 1 thru (Pos - 1) of timeStr as string
    set timeStr to characters (Pos + 1) through end of timeStr as string

    -- Get the "minute"
    set Pos to offset of ":" in timeStr
    set theMin to characters 1 thru (Pos - 1) of timeStr as string
    set timeStr to characters (Pos + 1) through end of timeStr as string

    --Get "AM or PM"
    set Pos to offset of " " in timeStr
    set theSfx to characters (Pos + 1) through end of timeStr as string

    return (**strong text**theHour & ":" & theMin & " " & theSfx) as string
end getTimeInHoursAndMinutes

顺便说一句,正确的方法是使用 launchctllaunchd

我根本不是 Applescript 专家,但通常认为坐着忙着等待反复检查时间的 CPU 是不好的做法 - 通常最好算出你想要多长时间做点什么,然后不消耗任何东西就睡觉 CPU 直到那个时候。

我通常在 bash shell 中做事,因为它对我来说似乎更简单,所以我会将时间转换为自 Unix 纪元(1970 年 1 月 1 日)以来的秒数,然后一切都很简单, 整数秒。所以,如果你进入终端并输入

date +%s
1420711428

目前距离大纪元已经过去了 1420711428 秒。如果我想知道今晚 18:00 大纪元以来的秒数,我只需在终端中输入:

date -j 1800.00 +%s
1420740000

现在,我知道我需要等待 1420740000 - 1420711428 秒直到 18:00。我可以在 shell 脚本中轻松做到这一点,并将您的 18:00:00 转换为 date 命令期望的格式,如下所示:

#!/bin/bash
#
# Get seconds till time specified by parameter
# Usage:
# till 18:00:00
# 
# Get current time in seconds since epoch
now=$(/bin/date +%s)
#echo now: $now

# Get passed in time in seconds since epoch
# Remove first colon and change second to a dot, so 18:00:00 becomes 1800.00 like "date" expects
t=${1/:/}
t=${t/:/.}
then=$(/bin/date -j $t +%s)
#echo then: $then

# Calculate difference
diff=$((then-now))
echo $diff

然后我将其保存为 till 并使用

使其可执行
chmod +x till

那我可以做

./till 18:00:00
28282

看到 18:00:00 之前是 28282 秒。

所以,我会将上面的脚本粘贴到您的 Applescript 中,然后使用

do shell script "<pasted code>"

然后简单地等待秒数直到你想要,或者将脚本的最后一行更改为 sleep $diff 这样脚本在你的计时器到期之前不会完成。

虽然我很欣赏 Mark Setchell 的回答,但由于您已经在使用 applescript,所以只需在 applescript 中计算直到下午 6 点的秒数。不需要专门的 shell 脚本来计算时间。试试这个...

set targetTime to "6:00:00 PM"
display dialog targetTime -- wait until we reach the target date/time

set curTime to current date
set futureTime to date (targetTime)
set secondsToFutureTime to futureTime - curTime

-- check if it's after 6PM on the current day
-- and if so then get 6PM on the next day
if secondsToFutureTime is less than 0 then
    set futureTime to futureTime + (1 * days)
    set secondsToFutureTime to futureTime - curTime
end if

delay secondsToFutureTime

tell application "Myapp" to activate