python指令碼實現在Mac上設定定時鬧鐘
阿新 • • 發佈:2018-12-12
起床鬧鐘自動播放音樂
背景:
預備每天早晨六點起床背單詞。但是,很不幸手機上的鬧鐘都會被隨手關掉,繼續睡。為了解決這個問題,決定在電腦上設定一個定時播放音樂的任務,畢竟,要關閉電腦上的鬧鐘,是需要從床上爬起來的。嗯,說幹就幹。
技術:
- Python:pygame
- Linux 下crontab指令
- Mac:
1、首先確認電腦上是否啟用cron指令
$LaunchAgents sudo launchctl list | grep cron
- 0 com.vix.cron
果然,在裡面,接下來檢查配置項
第一次使用locate命令報錯了,按照提示,執行命令:$LaunchAgents locate com.vix.cron WARNING: The locate database (/var/db/locate.database) does not exist. To create the database, run the following command: sudo launchctl load -w /System/Library/LaunchDaemons/com.apple.locate.plist Please be aware that the database can take some time to generate; once the database has been created, this message will no longer appear.
$LaunchAgents sudo launchctl load -w /System/Library/LaunchDaemons/com.apple.locate.plist
執行這個命令需要一點時間,且locate命令每次執行前都需要更新資料庫
$LaunchAgents sudo /usr/libexec/locate.updatedb
執行該命令不在報錯,則資料庫建立成功
重新執行命令:
$LaunchAgents locate com.vix.cron /System/Library/LaunchDaemons/com.vix.cron.plist
進入檔案
檔案內容:
注意:檔案裡面有一個KeepAlive的條件是:/etc/crontab是否存在,如果該檔案不存在,會導致定時任務不起作用<?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>com.vix.cron</string> <key>ProgramArguments</key> <array> <string>/usr/sbin/cron</string> </array> <key>KeepAlive</key> <dict> <key>PathState</key> <dict> <key>/etc/crontab</key> <true/> </dict> </dict> <key>QueueDirectories</key> <array> <string>/usr/lib/cron/tabs</string> </array> <key>EnableTransactions</key> <true/> </dict> </plist>
$LaunchAgents ll /etc/crontab
1)如果提示ll command not find
$LaunchAgents vim ~/.bash_profile
在該檔案中加入下面內容
14 # mac命令縮寫別名
15 alias ll='ls -alF'
16 alias la='ls -A'
17 alias l='ls -CF'
重啟檔案,使命令生效
$LaunchAgents source ~/.bash_profile
2)如果提示:
ls: /etc/crontab: No such file or directory
檔案不存在,先建立檔案
$LaunchAgents sudo touch /etc/crontab
執行指令碼:
提示 Permission denied 檔案沒有執行許可權,修改檔案許可權
chmod 777 cronStudy.sh
編寫指令碼檔案 alarmClock.py
新增定時任務
crontab -e
進入檔案,新增定時任務
52 5 * * * /Users/apple/Desktop/c/stg/linux/cronStudy.py > /dev/null 2>&1
定時每天早晨5點52開始啟動程式,關於crontab命令,請自行百度或谷歌