如何在特定时间开始使用AppleScript

时间:2014-08-15 21:57:16

标签: applescript

我正在尝试制作一个将在后台运行的AppleScript,并且只会在每周一次的特定时间执行任何建议吗?

2 个答案:

答案 0 :(得分:3)

你可能想要的是idle handler。首次打开AppleScript应用程序时(在完成“run”处理程序之后,如果它有一个,则立即调用空闲处理程序,否则立即执行)。

空闲处理程序返回的数字是下次运行空闲处理程序的秒数;也就是说,OS X将获取该数字,然后等待那么多秒再重新调用空闲处理程序。

这在实践中如何运作将取决于您需要“特定时间”的准确程度。例如,你可以让它返回7 * 24 * 60 * 60,每次空闲处理程序运行时,它也会在一周内再次运行。

或者,您可以在每次空闲处理程序运行时检查当前日期(包括当前时间),并使空闲处理程序返回24 * 60 * 60,从而每天进行自我检查;或60 * 60,每小时检查一次;或60,每分钟检查一次。

这是一个非常简单的空闲处理程序:它在星期五的某个时候显示一个恼人的“Hello”:

on idle
    -- if today is Friday, say something!
    set currentTime to current date
    if the weekday of currentTime is Friday then
        display dialog "Hello"
    end if

    --only check once a day
    return 24 * 60 * 60
end idle

这将特别检查星期五下午5点;它将每分钟检查当前时间:

on idle
    -- if today is Friday between 5 PM and 5:01 PM, say something!
    set currentTime to current date
    set fivePM to 17 * 60 * 60
    if the weekday of currentTime is Friday then
        if the time of currentTime is greater than fivePM and the time of currentTime is less than (fivePM + 60) then
            display dialog "Hello"
        end if
    end if

    --only check once a minute
    return 60
end idle

根据您的需要,您可能希望考虑使用属性来存储脚本上次执行的任何操作;在运行时间内维护属性,可用于防止电源故障后或在夏令时间界限之间重复执行。

答案 1 :(得分:3)

我实际上认为您尝试做的事情最适合发射服务。 (查看更多信息here

基本上,在Mac上,您可以配置放在计算机上指定目录中的.plist文件(如下所示)。 plist文件的设置告诉计算机何时运行以及要采取的操作。在您的情况下,您将其配置为在指定时间每周运行一次并告诉它启动您的脚本。这种方法的好处是你不必担心有人退出脚本,它不必一直在运行。它将在您指定的时间启动,完成它的工作然后退出。

示例.plist文件...

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
    <dict>
        <key>Label</key>
        <string>com.namespace.script_name</string>
        <key>Program</key>
        <string>/Applications/script_name.app/Contents/MacOS/applet</string>
        <key>LowPriorityIO</key>
        <true/>
        <key>Nice</key>
        <integer>1</integer>
        <key>StartInterval</key>
        <integer>7200</integer>
   </dict>
</plist>