Java定时任务取消的示例代码
java定时任务如何取消,并比如,我之前想每周二晚上6点自动生成一条devops流水线,现在我想停掉
答案: 在Java中,可以使用ScheduledExecutorService类来创建定时任务。要取消定时任务,可以调用ScheduledFuture对象的cancel()方法。
以下是一个示例代码,演示如何创建一个每周二晚上6点自动生成一条devops流水线的定时任务,并在需要时取消它:
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) {
// 创建一个ScheduledExecutorService对象
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
// 获取当前时间
Calendar now = Calendar.getInstance();
// 计算下一个周二晚上6点的时间
Calendar nextExecutionTime = getNextExecutionTime(now);
// 计算当前时间到下一个执行时间的时间间隔
long initialDelay = nextExecutionTime.getTimeInMillis() - now.getTimeInMillis();
// 创建定时任务
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);
// 在需要时取消定时任务
// future.cancel(true);
// 关闭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()方法创建了一个定时任务,该任务会在每周二晚上6点自动生成一条devops流水线。initialDelay参数表示当前时间到下一个执行时间的时间间隔,7 * 24 * 60 * 60 * 1000参数表示每隔7天执行一次。
要取消定时任务,可以调用future.cancel(true)方法。取消后,定时任务将不再执行。
请注意,上述代码中的取消和关闭操作是注释掉的。如果要取消定时任务,可以取消注释future.cancel(true);如果要关闭ScheduledExecutorService,可以取消注释executor.shutdown()。
到此这篇关于Java定时任务取消的示例代码的文章就介绍到这了,更多相关java定时任务取消内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
spring boot如何使用spring AOP实现拦截器
本篇文章主要介绍了spring boot如何使用spring AOP实现拦截器,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧2017-04-04
java中PriorityBlockingQueue的入队知识点总结
在本篇文章里小编给大家整理一篇关于java中PriorityBlockingQueue的入队知识点总结内容,有需要的朋友们可以学习下。2021-01-01
MyBatis中的@SelectProvider注解源码分析
这篇文章主要介绍了MyBatis中的@SelectProvider注解源码分析,@SelectProvider功能就是用来单独写一个class类与方法,用来提供一些xml或者注解中不好写的sql,今天就来说下这个注解的具体用法与源码,需要的朋友可以参考下2024-01-01


最新评论