您好,登錄后才能下訂單哦!
這期內(nèi)容當(dāng)中小編將會給大家?guī)碛嘘P(guān)使用ScheduledExecutorService怎么實(shí)現(xiàn)一個(gè)定時(shí)任務(wù),文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
示例代碼
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í)行某個(gè)任務(wù) <br> * 初始化延遲0ms開始執(zhí)行,每隔5ms重新執(zhí)行一次任務(wù)。 */ public void fixedRate(){ excutor.scheduleAtFixedRate(new EchoServer(), //執(zhí)行線程 0, //初始化延遲 5000, //兩次開始的執(zhí)行的最小時(shí)間間隔 TimeUnit.MILLISECONDS //計(jì)時(shí)單位 ); } /** * */ public void fixDelay(){ excutor.scheduleWithFixedDelay(new EchoServer(),//執(zhí)行線程 0, //初始化延遲 5000, //前一次執(zhí)行結(jié)束到下一次執(zhí)行開始的間隔時(shí)間 TimeUnit.MILLISECONDS); } /** * 每天晚上8點(diǎn)執(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í)間對應(yīng)的毫秒數(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怎么實(shí)現(xiàn)一個(gè)定時(shí)任務(wù)了,如果剛好有類似的疑惑,不妨參照上述分析進(jìn)行理解。如果想知道更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。