Java定時(shí)任務(wù)取消的示例代碼
java定時(shí)任務(wù)如何取消,并比如,我之前想每周二晚上6點(diǎn)自動生成一條devops流水線,現(xiàn)在我想停掉
答案: 在Java中,可以使用ScheduledExecutorService類來創(chuàng)建定時(shí)任務(wù)。要取消定時(shí)任務(wù),可以調(diào)用ScheduledFuture對象的cancel()方法。
以下是一個(gè)示例代碼,演示如何創(chuàng)建一個(gè)每周二晚上6點(diǎn)自動生成一條devops流水線的定時(shí)任務(wù),并在需要時(shí)取消它:
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)建一個(gè)ScheduledExecutorService對象
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
// 獲取當(dāng)前時(shí)間
Calendar now = Calendar.getInstance();
// 計(jì)算下一個(gè)周二晚上6點(diǎn)的時(shí)間
Calendar nextExecutionTime = getNextExecutionTime(now);
// 計(jì)算當(dāng)前時(shí)間到下一個(gè)執(zhí)行時(shí)間的時(shí)間間隔
long initialDelay = nextExecutionTime.getTimeInMillis() - now.getTimeInMillis();
// 創(chuàng)建定時(shí)任務(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);
// 在需要時(shí)取消定時(shí)任務(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)建了一個(gè)定時(shí)任務(wù),該任務(wù)會在每周二晚上6點(diǎn)自動生成一條devops流水線。initialDelay參數(shù)表示當(dāng)前時(shí)間到下一個(gè)執(zhí)行時(shí)間的時(shí)間間隔,7 * 24 * 60 * 60 * 1000參數(shù)表示每隔7天執(zhí)行一次。
要取消定時(shí)任務(wù),可以調(diào)用future.cancel(true)方法。取消后,定時(shí)任務(wù)將不再執(zhí)行。
請注意,上述代碼中的取消和關(guān)閉操作是注釋掉的。如果要取消定時(shí)任務(wù),可以取消注釋future.cancel(true);如果要關(guān)閉ScheduledExecutorService,可以取消注釋executor.shutdown()。
到此這篇關(guān)于Java定時(shí)任務(wù)取消的示例代碼的文章就介紹到這了,更多相關(guān)java定時(shí)任務(wù)取消內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Java實(shí)現(xiàn)并發(fā)執(zhí)行定時(shí)任務(wù)并手動控制開始結(jié)束
- Java定時(shí)任務(wù)Timer、TimerTask與ScheduledThreadPoolExecutor詳解
- Java?@Scheduled定時(shí)任務(wù)不執(zhí)行解決辦法
- Java實(shí)現(xiàn)定時(shí)任務(wù)的方法總結(jié)
- Java?Elastic-Job分布式定時(shí)任務(wù)使用方法介紹
- java實(shí)現(xiàn)周期性執(zhí)行(定時(shí)任務(wù))
- java8中定時(shí)任務(wù)最佳實(shí)現(xiàn)方式(實(shí)現(xiàn)原理)
相關(guān)文章
java之scan.next()與scan.nextline()函數(shù)的使用及區(qū)別
Java集合Iterator迭代的實(shí)現(xiàn)方法
spring-boot-plus V1.4.0發(fā)布 集成用戶角色權(quán)限部門管理(推薦)
Java基于二維數(shù)組實(shí)現(xiàn)的數(shù)獨(dú)問題示例

