標籤:crontab ubuntu jar
題記
之前使用solr進行全文檢索索引,涉及到檢索更新問題,這裡採用定時更新方法,現在使用的系統為ubuntu,因此考慮crontab.
解決思路
一.準備工具
二.編寫crontab 指令碼
過程
一.工具準備
1,製作jar包,可以通過java jar命令,也可以通過eclipse工具.
2.安裝crontab
ubuntu上安裝比較方便:
sudo apt-get install crontab
二.編寫crontab指令碼
1.認識crontab
Cron is a system daemon used to execute desired tasks (in the background) at designated times.
cron 屬於一個守護進程,用來在特定的時間執行指定的任務,一般是後台運行.定義表達的很明確,使用時要確定時間和命令即可.
格式也簡單:
minute (0-59), hour (0-23, 0 = midnight), day (1-31), month (1-12), weekday (0-6, 0 = Sunday), command
簡單例子:
* * * * * command
表示每一分鐘就執行一下command.
遇到的問題
(1)本身的java程式只是做一個測試,就是一個簡單的彈出對話方塊,在編寫crontab時候,出現沒有反應的情況.
查看log—>/var/log/syslog
可以發現在記錄檔中出現:No MTA installed, discarding output的問題.
根據尋找資料發現crontab執行指令碼時是不會直接錯誤的資訊輸出,而是會以郵件的形式發送到你的郵箱裡,這時候就需要郵件伺服器了,如果你沒有安裝郵件伺服器,它就會報這個錯。
通過在crontab指令碼後面添加> /dev/null 2>&1,可以解決這個問題,也就是表示先將標準輸出重新導向到/dev/null,然後將標準錯誤重新導向到標準輸出,由於標準輸出已經重新導向到了/dev/null,因此標準錯誤也會重新導向到/dev/null.
(2)開啟crontab日誌
- 修改rsyslog檔案,將
/etc/rsyslog.d/50-default.conf檔案中的#cron.*前的#刪掉;
- 重啟rsyslog服務
service rsyslog restart;
- 重啟cron服務
service cron restart;
重啟服務後,可還是沒有出現對話方塊,查看日誌沒有錯誤出現,這就很奇怪了.
之後發現要啟動GUI應用時候,需要啟動系統的display.
It is possible to run gui applications via cronjobs. This can be done by telling cron which display to use.
00 06 * * * env DISPLAY=:0 gui_appname
The env DISPLAY=:0 portion will tell cron to use the current display (desktop) for the program
可以在crontab裡面設定env DISPLAY,也可以在shell程式裡面添加:export DISPLAY=:0.0
DISPLAY=:0 The env DISPLAY=:0 portion will tell cron to use the current display (desktop) for the program “gui_appname”.
DISPLAY=:0.0 if you have multiple monitors, don’t forget to specify on which one the program is to be run. The env DISPLAY=:0.0 portion will tell cron to use the first screen of the current display for the program “gui_appname”.
總結
- 查看官方資料(
優選)及博文
- 遇到問題查看記錄檔,一般情況,日誌會記錄的很詳細
- 先從簡單的例子開始,逐步測試,為了驗證crontab是否運行 ,開始時候我就使用簡單寫入log功能測試,然後再進行java程式的測試
- 返回到第一步
附錄編寫代碼
crontab代碼:
每分鐘執行test.sh指令碼
PATH=/usr/sbin:/usr/bin:/sbin:/bin* * * * * /bin/bash /home/show_crontab/test.sh
test.sh指令碼:
#!/bin/bashcd /home/show_crontab #進入目錄export DISPLAY=:0.0 #啟動GUI顯示java -jar test.jar # 以防萬一,這裡的檔案最好寫成絕對路經
參考資料:
[1] https://help.ubuntu.com/community/CronHowto
[2]http://www.cnblogs.com/daxian2012/articles/2589894.html
[3]http://www.cnblogs.com/peida/archive/2013/01/08/2850483.html
[4]http://blog.csdn.net/huangyic1986/article/details/6731793
[5]http://bbs.chinaunix.net/thread-3650557-1-1.html
ubuntu 下使用crontab定時執行java程式