Java定時任務(wù)取消的示例代碼
java定時任務(wù)如何取消,并比如,我之前想每周二晚上6點自動生成一條devops流水線,現(xiàn)在我想停掉
答案: 在Java中,可以使用ScheduledExecutorService
類來創(chuàng)建定時任務(wù)。要取消定時任務(wù),可以調(diào)用ScheduledFuture
對象的cancel()
方法。
以下是一個示例代碼,演示如何創(chuàng)建一個每周二晚上6點自動生成一條devops流水線的定時任務(wù),并在需要時取消它:
import java.util.Calendar; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; public class Main { public static void main(String[] args) { // 創(chuàng)建一個ScheduledExecutorService對象 ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); // 獲取當前時間 Calendar now = Calendar.getInstance(); // 計算下一個周二晚上6點的時間 Calendar nextExecutionTime = getNextExecutionTime(now); // 計算當前時間到下一個執(zhí)行時間的時間間隔 long initialDelay = nextExecutionTime.getTimeInMillis() - now.getTimeInMillis(); // 創(chuàng)建定時任務(wù) ScheduledFuture<?> future = executor.scheduleAtFixedRate(new Runnable() { @Override public void run() { // 自動生成devops流水線的代碼 System.out.println("Generating devops pipeline..."); } }, initialDelay, 7 * 24 * 60 * 60 * 1000, TimeUnit.MILLISECONDS); // 在需要時取消定時任務(wù) // future.cancel(true); // 關(guān)閉ScheduledExecutorService // executor.shutdown(); } private static Calendar getNextExecutionTime(Calendar now) { Calendar nextExecutionTime = (Calendar) now.clone(); nextExecutionTime.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY); nextExecutionTime.set(Calendar.HOUR_OF_DAY, 18); nextExecutionTime.set(Calendar.MINUTE, 0); nextExecutionTime.set(Calendar.SECOND, 0); nextExecutionTime.set(Calendar.MILLISECOND, 0); if (nextExecutionTime.before(now)) { nextExecutionTime.add(Calendar.WEEK_OF_YEAR, 1); } return nextExecutionTime; } }
在上述代碼中,我們使用ScheduledExecutorService
的scheduleAtFixedRate()
方法創(chuàng)建了一個定時任務(wù),該任務(wù)會在每周二晚上6點自動生成一條devops流水線。initialDelay
參數(shù)表示當前時間到下一個執(zhí)行時間的時間間隔,7 * 24 * 60 * 60 * 1000
參數(shù)表示每隔7天執(zhí)行一次。
要取消定時任務(wù),可以調(diào)用future.cancel(true)
方法。取消后,定時任務(wù)將不再執(zhí)行。
請注意,上述代碼中的取消和關(guān)閉操作是注釋掉的。如果要取消定時任務(wù),可以取消注釋future.cancel(true)
;如果要關(guān)閉ScheduledExecutorService
,可以取消注釋executor.shutdown()
。
到此這篇關(guān)于Java定時任務(wù)取消的示例代碼的文章就介紹到這了,更多相關(guān)java定時任務(wù)取消內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
java之scan.next()與scan.nextline()函數(shù)的使用及區(qū)別
這篇文章主要介紹了java之scan.next()與scan.nextline()函數(shù)的使用及區(qū)別,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-04-04spring-boot-plus V1.4.0發(fā)布 集成用戶角色權(quán)限部門管理(推薦)
這篇文章主要介紹了spring-boot-plus V1.4.0發(fā)布 集成用戶角色權(quán)限部門管理,本文給大家介紹的非常詳細,具有一定的參考借鑒價值需要的朋友可以參考下2019-11-11Java基于二維數(shù)組實現(xiàn)的數(shù)獨問題示例
這篇文章主要介紹了Java基于二維數(shù)組實現(xiàn)的數(shù)獨問題,涉及java針對數(shù)組的遍歷、計算、轉(zhuǎn)換等相關(guān)操作技巧,需要的朋友可以參考下2018-01-01