這期內(nèi)容當中小編將會給大家?guī)碛嘘P使用ScheduledExecutorService怎么實現(xiàn)一個定時任務,文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
在渾江等地區(qū),都構建了全面的區(qū)域性戰(zhàn)略布局,加強發(fā)展的系統(tǒng)性、市場前瞻性、產(chǎn)品創(chuàng)新能力,以專注、極致的服務理念,為客戶提供網(wǎng)站設計、成都做網(wǎng)站 網(wǎng)站設計制作定制網(wǎng)站,公司網(wǎng)站建設,企業(yè)網(wǎng)站建設,品牌網(wǎng)站制作,營銷型網(wǎng)站建設,成都外貿(mào)網(wǎng)站制作,渾江網(wǎng)站建設費用合理。
示例代碼
package com.effective.common.concurrent.execute; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class Schedule { private static DateFormat dateFormat = new SimpleDateFormat("yy-MM-dd HH:mm:ss"); private static DateFormat dayFormat = new SimpleDateFormat("yy-MM-dd"); private static ScheduledExecutorService excutor = Executors.newSingleThreadScheduledExecutor(); /** * 按指定頻率周期執(zhí)行某個任務 <br> * 初始化延遲0ms開始執(zhí)行,每隔5ms重新執(zhí)行一次任務。 */ public void fixedRate(){ excutor.scheduleAtFixedRate(new EchoServer(), //執(zhí)行線程 0, //初始化延遲 5000, //兩次開始的執(zhí)行的最小時間間隔 TimeUnit.MILLISECONDS //計時單位 ); } /** * */ public void fixDelay(){ excutor.scheduleWithFixedDelay(new EchoServer(),//執(zhí)行線程 0, //初始化延遲 5000, //前一次執(zhí)行結束到下一次執(zhí)行開始的間隔時間 TimeUnit.MILLISECONDS); } /** * 每天晚上8點執(zhí)行一次 */ public void dayOfDelay(String time){ ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); long oneDay = 24 * 60 * 60 * 1000; long initDelay = getTimeMillis("20:00:00") - System.currentTimeMillis(); initDelay = initDelay > 0 ? initDelay : oneDay + initDelay; executor.scheduleAtFixedRate( new EchoServer(), initDelay, oneDay, TimeUnit.MILLISECONDS); } /** * 獲取給定時間對應的毫秒數(shù) * @param string "HH:mm:ss" * @return */ private static long getTimeMillis(String time) { try { Date currentDate = dateFormat.parse(dayFormat.format(new Date()) + " " +time); return currentDate.getTime() ; } catch (ParseException e) { e.printStackTrace(); } return 0; } public static void main(String[] args){ Schedule schedule = new Schedule(); schedule.fixedRate(); schedule.fixDelay(); } }
上述就是小編為大家分享的使用ScheduledExecutorService怎么實現(xiàn)一個定時任務了,如果剛好有類似的疑惑,不妨參照上述分析進行理解。如果想知道更多相關知識,歡迎關注創(chuàng)新互聯(lián)行業(yè)資訊頻道。
分享文章:使用ScheduledExecutorService怎么實現(xiàn)一個定時任務
網(wǎng)頁路徑:http://chinadenli.net/article32/gogspc.html
成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供面包屑導航、做網(wǎng)站、手機網(wǎng)站建設、搜索引擎優(yōu)化、網(wǎng)站內(nèi)鏈、域名注冊
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉載內(nèi)容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)