Java 根据Cron表达式获取近几次任务执行时间

news/2024/9/22 7:36:28

这篇博客将介绍Java 如何根据Cron表达式获取近几次任务执行时间。实际上使用 quartzCronSequenceGenerator 以及TriggerUtils.computeFireTimes 俩种方法进行时间获取;

1. 效果图

在这里插入图片描述

2. 源码

<dependency><groupId>org.quartz-scheduler</groupId><artifactId>quartz</artifactId><version>2.3.0</version>
</dependency>
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.quartz.CronExpression;
import org.quartz.TriggerUtils;
import org.quartz.impl.triggers.CronTriggerImpl;
import org.springframework.scheduling.support.CronSequenceGenerator;import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.Consumer;/****************************** Class Name: CronUtil* Description: <获取Cron表达式最近几次执行的时间>* @Author: Seminar* @create: 2022/11/02* @since: 1.0.0***************************/
@Slf4j
public class CronUtil {public void getTime() {String cronExpress = "0 */30 * * * ?";//此处为cron表达式cronExpress = "0 0/30 * * * ?";try {CronExpression cronExpression = new CronExpression(cronExpress);//导包import org.quartz.CronExpression;Date date = cronExpression.getTimeAfter(new Date());//将date转换为指定日期格式字符串SimpleDateFormat dataFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");String dateString = dataFormat.format(date);//dateString为转换后的日期格式log.info("{} {}", cronExpress, dateString);} catch (Exception e) {log.error("cron获取下次执行时间异常" + e);}}/*** 列出近cronCount次的执行时间** @param cronExpression cron表达式* @param cronCount      cron时间次数* @param maxCronCount   最大cron时间次数* @return*/public static List<String> listCronRunTime(String cronExpression, Integer cronCount, Integer maxCronCount) {if (StringUtils.isBlank(cronExpression)) {throw new RuntimeException("Cron 表达式不能为空!");}if (!CronSequenceGenerator.isValidExpression(cronExpression)) {throw new RuntimeException("Cron格式不正确,Cron: " + cronExpression);}if (cronCount < 1) {cronCount = 1;}if (maxCronCount < 1) {maxCronCount = 100;}if (cronCount > maxCronCount) {cronCount = maxCronCount;}CronSequenceGenerator cronSequenceGenerator = new CronSequenceGenerator(cronExpression);List<String> cronTimeList = new ArrayList<>();Date nextTimePoint = new Date();SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");for (int i = 0; i < cronCount; i++) {nextTimePoint = cronSequenceGenerator.next(nextTimePoint);cronTimeList.add(sdf.format(nextTimePoint));}return cronTimeList;}/*** 列出近numTimes次的执行时间** @param cronExpression cron表达式* @param numTimes       下几次运行时间* @return*/public static List<String> getNextExecTime(String cronExpression, Integer numTimes) {List<String> list = new ArrayList<>();CronTriggerImpl cronTriggerImpl = new CronTriggerImpl();try {cronTriggerImpl.setCronExpression(cronExpression);} catch (ParseException e) {e.printStackTrace();}// 这个是重点,一行代码搞定List<Date> dates = TriggerUtils.computeFireTimes(cronTriggerImpl, null, numTimes);SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");for (Date date : dates) {list.add(dateFormat.format(date));}return list;}/*** Java8 通过foreach 遍历List,同时输出下标* 利用BiConsumer实现foreach循环支持index** @param biConsumer* @param <T>* @return*/public static <T> Consumer<T> forEachWithIndex(BiConsumer<T, Integer> biConsumer) {/*这里说明一下,我们每次传入forEach都是一个重新实例化的Consumer对象,在lambada表达式中我们无法对int进行++操作,我们模拟AtomicInteger对象,写个getAndIncrement方法,不能直接使用AtomicInteger哦*/class IncrementInt {int i = 0;public int getAndIncrement() {return i++;}}IncrementInt incrementInt = new IncrementInt();return t -> biConsumer.accept(t, incrementInt.getAndIncrement());}public static void main(String[] args) {CronUtil cronUtil = new CronUtil();cronUtil.getTime();String cron = "0 0/30 * * * ?"; // 0 0/30 * * * ? 每隔30分钟执行一次 同 0 */30 * * * ?cron = "0 0/5 14 * * ?"; // 0 0/5 14 * * ? 在每天下午2点到下午2:55期间的每5分钟触发log.info("cron: {}", cron);List<String> timeList = listCronRunTime(cron, 10, 100);timeList.stream().forEach(forEachWithIndex((item, index) -> {log.info("{} {}", index + 1, item);}));List<String> time2List = getNextExecTime(cron, 10);time2List.stream().forEach(x -> {log.info("---- {}", x);});}
}

参考

  • 根据Cron表达式获取近几次任务执行时间(Spring + Quartz)
  • cron表达式详解,cron表达式写法,cron表达式例子
  • 根据cron表达式获取下次执行时间

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.pgtn.cn/news/17517.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈,一经查实,立即删除!

相关文章

使用Python,OpenCV对图像进行亚像素点检测,并拟合椭圆进行绘制

这篇博客将介绍如何使用Python&#xff0c;OpenCV对图像进行亚像素检测&#xff0c;并对亚像素点进行椭圆拟合绘制。 1. 效果图 原始图上绘制拟合椭圆 VS 原始图上绘制拟合椭圆及亚像素点绘制随机半径及颜色的圆 VS 灰度图上绘制亚像素点效果图如下&#xff1a; 我喜欢的颖宝…

Android控件之ImageView探究

ImageView控件是一个图片控件&#xff0c;负责显示图片。 以下模拟手机图片查看器 目录结构 main.xml布局文件 <?xml version"1.0"encoding"utf-8"?><LinearLayout xmlns:android"http://schemas.android.com/apk/res/android"androi…

使用make_blob,KNeighborsClassifier-K近邻算法进行分类

写这篇博客源于博友的提问&#xff1a; 1. 效果图 输入 100 5 3 7 得到结果 [2] 可视化效果图如下&#xff1a;待预测点红色x展示&#xff0c; 输入 88 2 1 9 得到结果&#xff1a; [1] 可视化效果图如下&#xff1a;待预测点红色x展示&#xff0c; 2. 源码 # KNeighbo…

一生受益的三个小故事

转载于:https://www.cnblogs.com/88223100/archive/2011/02/22/three_stories.html

使用matplotlib绘制定制化饼图(图例比例标签支持中文等)

写这篇博客源于博友的提问 1. 效果图 效果图如下&#xff1a; 2. 原理 autopct‘%0.1f%%’ 自动添加百分比显示&#xff0c;格式化保留1位小数labeldistance 设置各扇形标签&#xff08;图例&#xff09;与圆心的距离&#xff08;labeldistance&#xff09;为1.1shadowTrue…

Python字母数字下划线生成田字格随机密码

写这篇博客源于博友的提问1&#xff0c;提问2 1. 效果图 10行随机密码&#xff0c;首字母不同&#xff0c;效果图如下&#xff1a; 田字格随机字符串如下&#xff1a; 2. 源码 # 生成随机密码 import randomimport numpy as np# 1. 生成随机密码,密码首字母不同 np.rando…

NHibernate从入门到精通系列(7)——多对一关联映射

内容摘要 多对一关联映射概括 多对一关联映射插入和查询 多对一关联映配置介绍 一、多对一关联映射概括 关联关系是实体类与实体类之间的结构关系&#xff0c;分别为“多对一”、“一对一”、“多对多”。然而“多对一”是怎样描述的呢&#xff1f;让我们参考图1.1所示&#xf…

使用Python爬取信息403解决,并统计汇总绘制直方图,柱状图,折线图

使用Python爬取信息403解决&#xff0c;并统计汇总绘制直方图&#xff0c;柱状图&#xff0c;折线图 写这篇博客源于博友的提问&#xff1a; 1. 效果图 拟录取专业-人数分布直方图效果图如下&#xff1a; 拟录取专业-人数效果图如下&#xff1a; 拟录取专业-人数柱状图…