Java 中要定時執行某個動作,有三種選擇:
1、Timer 和 TimerTask
2、ScheduledExecutorService
3、quartz 套件
原本我是用 1 的方法來實作定時執行,但後來遇到 Timer 的 thread 難以控制的問題
如果定時執行到一半突然必須強制關閉時,Timer 很難做到讓我找出它的 thread 並且關掉
在查了一些資料後看到這篇文章:Java Timer vs ExecutorService?
其中回應裡有一段「ScheduledThreadPoolExecutor can be configured with any number of threads. Furthermore, you have full control over created threads, if you want (by providing ThreadFactory)」
而 quartz 因為不明原因把網路上找到的 sample code 貼上去以後程式就爆了
而且有看到有文章說 ScheduledExecutorService 是比較底層的 API,雖然很多事情要自己做
但也因此能夠自己對 Thread 有比較完整的控制權
因此最後是決定改用 ScheduledExecutorService 來實作定時執行。
Software entities (class, modules, functions, etc.) should be open for extension, but closed for modification.
- Bertrand Meyer
Junior programmers create simple solutions to simple problems. Senior programmers create complex solutions to complex problems. Great programmers find simple solutions to complex problems.
- Charles Connell
註1:本部落格的範例程式碼在 2015 年以前的文章中,大多是以全型空白做縮排。如需服用,請自行用文字編輯器的取代功能把全型空白取代成半型空白。
註2:本部落格的內容授權請參閱部落格底部的授權宣告。
2011年11月29日 星期二
Java 定時執行 (1)
2011年11月16日 星期三
eclipse 更換不同編輯套件
在 eclipse 上安裝了 Aptana 套件,但是用 eclipse 開啟 html 或者 js 檔的時候
預設還是會用 eclipse 自己原生的 html editor
今天突然發現原來只要設定檔案關聯就好了!XD
Window → Preferences → General → Editors → File Associations
在上半部的框框中選擇要變更的副檔名
選定後下面的框框會列出可用的編輯器
可以把想要的編輯器設為預設(點右邊的 default),下次開啟時就會自動用指定的編輯器開啟了!
2011年11月4日 星期五
jQuery 讀取 JSONArray 的方法
一般透過 $.ajax 送 JSON 格式的資料給後端處理
後端回應一個 JSON 回來,都可以直接用 .xxx 來存取回應的 JSON
例如回應的 JSON 是 {"statuscode", 200}
可以直接用:
1 2 3 4 5 6 7 8 9 10 11 12 |
$.ajax({ type: "GET" , url: endpoint, contentType: "application/json" , dataType: "json" , success: function (data){ consile.log( "statuscode: " + data.statuscode); }, error: function (){ unblock(); // TODO } }); |
這樣在 FireFox 的 FireBug 中就會跑出:「statuscode: 200」的記錄。
當回應的 JSON 是個巢狀的 JSON array 時,則處理方式稍微複雜一點點