代码之家  ›  专栏  ›  技术社区  ›  gabriel119435

为什么这个cron模式不是每37秒匹配/运行一次?

  •  0
  • gabriel119435  · 技术社区  · 6 年前

    我有一个具有以下属性的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));
    }
    

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

    我以为cron的意思是“每37秒运行一次”,但事实并非如此。

    * * * * * * 我知道了:

    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
    

    这是有道理的:在前一次执行完成后,需要1s才能开始新的执行,总是需要5s才能完成。但当我用 */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
    

    @fixedDelay 但在某些属性文件中可以灵活更改( @固定延迟 仅接受常量)。

    1 回复  |  直到 6 年前
        1
  •  2
  •   Menelaos    6 年前

    我不认为只有cron才能做到这一点,比如37。

    基本上是等于(或小于)30的偶数。

    对于10,您的表达式是:

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

    0 * * * * *