我是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
答案 0 :(得分:3)
虽然我很欣赏Mark Setchell的回答,因为你已经在使用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
答案 1 :(得分:1)
顺便说一句,正确的方法是使用launchctl
和launchd
。
我根本不是Applescript专家,但通常被认为是不好的做法,坐在忙着等待CPU反复检查时间 - 通常最好弄清楚它需要多长时间才能做某事然后只是在此之前没有消耗任何CPU就睡不着。
我通常在bash
shell中做一些事情,因为它对我来说似乎更简单,所以我会将自从Unix Epoch(1970年1月1日)以来的时间转换为秒,然后一切都很简单,整数秒。所以,如果你进入终端并输入
date +%s
1420711428
目前是Epoch以来的1420711428秒。如果我想知道今晚18点以来大纪元以来的秒数,我只需在终端输入:
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
看到它是28282秒直到18:00:00。
因此,我会将上面的脚本粘贴到您的Applescript中,然后使用
do shell script "<pasted code>"
只需等待所需的秒数,或者将脚本的最后一行更改为sleep $diff
,这样脚本就会在计时器到期之前完成。