ScheduledExecutorService任務(wù)定時(shí)代碼示例
本文主要分享了一則關(guān)于ScheduledExecutorService任務(wù)定時(shí)的實(shí)例代碼,具體如下:
示例代碼
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í)間對(duì)應(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(); } }
總結(jié)
以上就是本文關(guān)于ScheduledExecutorService任務(wù)定時(shí)代碼示例的全部內(nèi)容,希望對(duì)大家有所幫助。感興趣的朋友可以繼續(xù)參閱本站其他相關(guān)專題,如有不足之處,歡迎留言指出。感謝朋友們對(duì)本站的支持!
相關(guān)文章
java算法之Math.random()隨機(jī)概率玩法實(shí)例演示
最近打算整理排序算法,發(fā)現(xiàn)很有必要準(zhǔn)備一下生成隨機(jī)數(shù)的工具類,下面這篇文章主要給大家介紹了關(guān)于java算法之Math.random()隨機(jī)概率玩法的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-05-05詳解java中Reference的實(shí)現(xiàn)與相應(yīng)的執(zhí)行過程
不知道大家知不知道特殊的reference對(duì)象都是被jvm專門處理的,所以這篇文章就相應(yīng)的工作流程和referencequeue之間的協(xié)作進(jìn)行梳理.有需要的朋友們可以參考借鑒。2016-09-09Java常用類庫StringBuffer,Runtime,日期操作類等類庫總結(jié)
這篇文章主要介紹了Java常用類庫StringBuffer,Runtime,日期操作類等類庫總結(jié),需要的朋友可以參考下2020-02-02MyBatisPlus分頁時(shí)排序的實(shí)現(xiàn)
本文主要介紹了MyBatisPlus分頁時(shí)排序的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-03-03