14

假设我有一个CronTriggerBean类似的

<bean id="midMonthCronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
    <property name="jobDetail" ref="reminderJobDetail" />
    <property name="cronExpression" value="0 0 6 15W * ?" />
</bean>

测试该 bean 是否会在其指定日期(最接近每月 15 日的工作日早上 6 点)实际触发的最佳方法是什么?


更新:这应该是一个单元测试,所以我不会启动虚拟机或更改系统时间。

4

6 回答 6

19

首先,测试CronTriggerBean本身没有意义。它是 spring 框架的一部分,并且已经过测试。

更好的测试可能是测试您的 cron 表达式是否符合您的期望。这里的一种选择是使用 Quartz 的CronExpression类。给定一个CronExpression对象,您可以调用getNextValidTimeAfter(Date),它会在给定日期之后的下一次触发表达式时返回。

于 2009-06-29T21:50:03.703 回答
7

我使用 CronMaker 只是为了确定我的 cron 表达式是否格式正确,请查看: http ://www.cronmaker.com/

于 2012-03-23T19:32:41.870 回答
3
  1. 您可以一直等到 7 月 15 日。
  2. 更认真...如果它真的是应用程序的关键部分,我需要对其进行全面测试。我建议使用一些虚拟化设置并将应用程序安装在一些来宾机器中。然后,您可以使用系统时钟并测试不同的日期/时间,而无需花费整整一个月的时间。此外,没有什么可以阻止您自动执行此类测试。
于 2009-06-29T21:16:02.120 回答
2

对于那些不使用 Quartz 调度器,而是TaskSchedular直接使用:

CronSequenceGenerator generator = new CronSequenceGenerator("0 0 8 */1 * *");
Date next = generator.next(prev);
于 2013-05-13T14:18:30.590 回答
1

您还可以从 spring 中获取 trigger bean 并调用该getFireTimeAfter方法来完成。

于 2011-01-17T05:34:52.613 回答
0

我在这里找到了一个关于测试的很酷的文档CronExpressionhttp ://www.nurkiewicz.com/2012/10/testing-quartz-cron-expressions.html

C# 实现将是这样的:

void Run()
{
    //var collection = findTriggerTimesRecursive(new CronExpression("0 0 17 L-3W 6-9 ? *"), DateTime.UtcNow);
    var collection = findTriggerTimesRecursive(new CronExpression("0 0/15 * 1/1 * ? *"), DateTime.UtcNow);
    Console.WriteLine(DateTime.UtcNow);
    foreach (var item in collection)
    {
        Console.WriteLine(item);
    }
}

public List<DateTimeOffset> findTriggerTimesRecursive(CronExpression expr, DateTimeOffset from, int max = 10)
{
    var times = new List<DateTimeOffset>();
    var next = expr.GetNextValidTimeAfter(from);

    while (next != null && times.Count < max)
    {
        times.Add(next.Value);
        from = next.Value;
        next = expr.GetNextValidTimeAfter(from);
    }

    return times;
}

This is a cool demo. But at the end, I end using Simple Schedule.

var trigger = TriggerBuilder.Create()
    .WithIdentity("trigger3", "group1")
    .WithSimpleSchedule(
        x =>
        {
            x.WithIntervalInMinutes(15);
            x.RepeatForever();
        }
    )
    .ForJob("myJob", "group1")
    .Build();

Because this is executed immediately and then every x time.

于 2016-05-10T21:42:31.753 回答