Java定時任務ScheduledThreadPoolExecutor

來源:互聯網
上載者:User

以前定時任務一直用Timer這個類,後來發現ScheduledThreadPoolExecutor功能更強大,我們先看個簡單的樣本,然後再看看API中的描述:

這個定時任務是我的項目中,每隔5分鐘去檢查裝置的線上狀態的。

public class CheckDeviceStateExcuter {private static final Log log = LogFactory.getLog(CheckDeviceStateExcuter.class);private static final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);private static DeviceDao deviceDao = new DeviceDaoImpl();private static List<DeviceDTO> devices = new ArrayList<DeviceDTO>();// invoke DLL method to get the details of devicestatic JoymindCommDLLLib instance = JoymindCommDLLLib.INSTANCE;// check statespublic static void checkStart() {final Runnable checker = new Runnable() {public void run() {System.out.println("check");devices = deviceDao.queryDevices();for(DeviceDTO device : devices){String ip = device.getIp();String id = "auto_refresh_" + ip;String iniPath = XmlOperationTool.PLAYLIST_TEMPFILE_FOLDER + id+ ".ini";int flag = instance.GetSysInfo(ip, iniPath);if(flag == 1){// get ini fileSystemInfoDTO info = null;try {info = FileOperationTool.parseIni(iniPath);device.setMacAdd(info.getMacAddress());device.setIp(info.getIp());device.setGateway(info.getGateway());device.setOnlineState("線上");device.setBootTime(info.getBootTime());device.setDeviceVersion(info.getVersion());device.setAvailableSpace(info.getFreedisk());device.setpNo(info.getpNo());device.setWidth(info.getWidth());device.setHeight(info.getHeight());device.setStorage(info.getStorage());device.setTime(info.getTime());device.setPrgTotal(info.getPrgTotal());device.setPrgIndex(info.getPrgIndex());device.setStatusNo(info.getStatus());if (info.getStorage().equals("1")) {device.setStorageName("FLASH儲存");}if (info.getStorage().equals("2")) {device.setStorageName("RAM儲存");}if (info.getStorage().equals("3")) {device.setStorageName("SD卡儲存");}device.setCurrentPlaylist("");device.setCurrentTemplate("");device.setLastCommunicateTime("");device.setCurrentTransferFileName("");device.setCurrentTransferSpeed("");device.setCurrentPercentage("");device.setVolume("");device.setAutoBootTime("");device.setAutoShutdownTime("");device.setPlayingVideo("");device.setProgramUpdateTime("");device.setProgramUpdateState("");} catch (IOException e1) {if (log.isErrorEnabled()) {log.error(e1.getMessage());}e1.printStackTrace();}boolean addFlag = deviceDao.updateDevice(device);if (addFlag) {if (log.isDebugEnabled()) {log.debug("auto update device "+device.getName()+" successfully");}} else {if (log.isErrorEnabled()) {log.error("auto update device failed !!!");}}}else{deviceDao.updateDevice(ip, "離線");if (log.isDebugEnabled()) {log.debug("auto update device "+device.getName()+" statue offline");}}}}};// 此處的checker是一個線程,1表示啟動延遲1個單位開始執行這個線程,然後每隔5分鐘執行一次,單位是分鐘 final ScheduledFuture<?> checkerHandle = scheduler.scheduleAtFixedRate(checker, 1, 5, TimeUnit.MINUTES);// 這裡注釋的地方是取消這個定時任務的,是在3600天后停止,因為我這裡是檢查裝置的,所以除非當程式退出才自動停止這個定時任務 /*scheduler.schedule(new Runnable() {public void run() {checkerHandle.cancel(true);}}, 60 * 60, TimeUnit.DAYS);*/}/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stub}

再看看API的具體資訊,總之這是個非常實用的類

public class ScheduledThreadPoolExecutor
extends ThreadPoolExecutor
implements ScheduledExecutorService

ThreadPoolExecutor,它可另行安排在給定的延遲後運行命令,或者定期執行命令。需要多個輔助線程時,或者要求ThreadPoolExecutor
具有額外的靈活性或功能時,此類要優於
Timer。

一旦啟用已延遲的任務就執行它,但是有關何時啟用,啟用後何時執行則沒有任何即時保證。按照提交的先進先出 (FIFO) 順序來啟用那些被安排在同一執行時間的任務。

雖然此類繼承自
ThreadPoolExecutor,但是幾個繼承的調整方法對此類並無作用。特別是,因為它作為一個使用 corePoolSize 線程和一個無界隊列的固定大小的池,所以調整maximumPoolSize 沒有什麼效果。

擴充注意事項:此類重寫
AbstractExecutorService 的 submit 方法,以產生內部對象控制每個任務的延遲和調度。若要保留功能性,子類中任何進一步重寫的這些方法都必須調用超類版本,超類版本有效地禁用附加任務的定製。但是,此類提供替代受保護的擴充方法decorateTask(為
Runnable 和 Callable 各提供一種版本),可定製用於通過 execute、submit、schedule、scheduleAtFixedRate 和
scheduleWithFixedDelay 進入的執行命令的具體任務類型。預設情況下,ScheduledThreadPoolExecutor 使用一個擴充FutureTask 的任務類型。但是,可以使用下列形式的子類修改或替換該類型。

 public class CustomScheduledExecutor extends ScheduledThreadPoolExecutor {   static class CustomTask<V> implements RunnableScheduledFuture<V> { ... }   protected <V> RunnableScheduledFuture<V> decorateTask(                Runnable r, RunnableScheduledFuture<V> task) {       return new CustomTask<V>(r, task);   }   protected <V> RunnableScheduledFuture<V> decorateTask(                Callable<V> c, RunnableScheduledFuture<V> task) {       return new CustomTask<V>(c, task);   }   // ... add constructors, etc. } 

從以下版本開始:
1.5

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.