
我正在嘗試編寫一個小腳本,作為一個函數,它會將文件和日期作為輸入,並在指定的日期刪除該文件。所以我只需要安排它運行一次,僅此而已。
我在 OSX 上並且一直在看在,但我不僅在編寫它的腳本時遇到了問題,而且據我了解(我一整天都在研究)類似的服務將在 OSX 上被棄用at
,cron
以支持launchd
.
從我所見,不僅 launchd 對此過於複雜,而且我似乎不知道如何使用它在特定時間和日期執行一次性操作(這確實是我所需要的)。
我想在這方面得到一些幫助,請。我寧願不使用在,理想情況下它是一個不需要用戶安裝額外東西的解決方案。它還需要可編寫腳本(因此,命令列)。如果我必須使用launchd
,那就這樣吧,但它確實需要能夠使用特定的時間和日期。
答案1
當然 cron 和 at 已被棄用,但它們可能不會去任何地方(即使它們去了,重新安裝它們並不難)。
如果您確實想使用 launchd 執行此操作,則必須在第一個腳本中儲存並載入屬性列表,然後在第二個腳本中卸載並刪除它。
#!/bin/bash
month=6
day=1
hour=18
minute=0
label=com.superuser.431145
agent=~/Library/LaunchAgents/$label.plist
plist="<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<!DOCTYPE plist PUBLIC -//Apple Computer//DTD PLIST 1.0//EN
http://www.apple.com/DTDs/PropertyList-1.0.dtd>
<plist version=\"1.0\">
<dict>
<key>Label</key>
<string>$label</string>
<key>ProgramArguments</key>
<array>
<string>/path/to/script</string>
</array>
<key>StartCalendarInterval</key>
<array>
<dict>
<key>Month</key>
<integer>$month</integer>
<key>Day</key>
<integer>$day</integer>
<key>Hour</key>
<integer>$hour</integer>
<key>Minute</key>
<integer>$minute</integer>
</dict>
</array>
</dict>
</plist>"
echo "$plist" > $agent
launchctl unload $agent 2> /dev/null
launchctl load $agent
第二個腳本可能如下所示:
plist=~/Library/LaunchAgents/com.superuser.431145.plist
launchctl unload $plist
rm $plist
rm ~/Desktop/test
如果您使用 at,則首先必須使用 啟用它sudo launchctl load -w /System/Library/LaunchDaemons/com.apple.atrun.plist
。以下是從我的網站複製的一些範例:
echo 'say test' | at now+5 # +5 and +5 seconds don't work
echo 'say test' | at +1 minute # +1 minutes results in an error
echo 'say test' | at +2 hours
echo say test > test.txt; at -f test.txt now+5
atq # at -l; list at queue
atrm 14 # at -d 14
atrm {1..9999} # remove all jobs