为什么这个 cron 模式不是每 37 秒 match/run?

Why this cron pattern doesn't match/run every 37 seconds?

我有一个 Spring 应用程序 属性:

cobra.tarifas.intervaloEntreCobrancas =*/37 * * * * *

这是它的用处:

@Scheduled(cron = "${cobra.tarifas.intervaloEntreCobrancas}")
public void cobraTarifaDMaisZero() {

    int number = new Random().nextInt();

    System.out.println("started " + number + " at " + LocalTime.now().withNano(0));
    try {
        Thread.sleep(5000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    System.out.println("finished " + number + " at " + LocalTime.now().withNano(0));
}

所以每次它运行时我都有一个日志指出它何时开始和结束,以及一个 "unique" 标识符(Spring 在 @Scheduled [=40 使用相同的实例=] 没有额外的配置,this.toString 每次都返回相同的字符串)。每次执行需要 5 秒才能完成。

我以为 cron 表达式的意思是 "runs everytime every 37 seconds",但事实并非如此。

使用 * * * * * * 我得到了这个:

started -1615036471 at 10:18:46
finished -1615036471 at 10:18:51
started 2090620070 at 10:18:52
finished 2090620070 at 10:18:57
started -349207943 at 10:18:58
finished -349207943 at 10:19:03

这是有道理的:在前一个执行完成后需要 1 秒才能开始新的执行,总是需要 5 秒才能完成。但是当我使用 */37 * * * * * 我得到了

started -644623959 at 10:54
finished -644623959 at 10:54:05
started 212117957 at 10:54:37
finished 212117957 at 10:54:42
started 1788724609 at 10:55
finished 1788724609 at 10:55:05
started 362510867 at 10:55:37
finished 362510867 at 10:55:42
started -25103618 at 10:56
finished -25103618 at 10:56:05
started -820939074 at 10:56:37
finished -820939074 at 10:56:42

为什么它只在第 00 秒和第 37 秒开始?我想实现与 Spring 的 @fixedDelay 类似的行为,但可以灵活地在某些属性文件中进行更改(@fixedDelay 只接受常量)。

我不认为您实际上只能使用 cron 来执行此操作,对于诸如 37 之类的数字。

最简单的选择是 select 可以整除 60 的增量。 基本上是等于(或小于)30 的偶数。

例如所以 10、15、20 或 30。

对于 10,您的表达式将是:

cobra.tarifas.intervaloEntreCobrancas =0,10,20,30,40,50 * * * * *

要不然你一分钟只去一次。

0 * * * * *