【问题标题】:Cron expression of every 3 minutes between specific time特定时间之间每 3 分钟的 Cron 表达式
【发布时间】:2020-10-16 08:28:33
【问题描述】:

这是场景:- 我想在我的 NodeJs 应用程序中运行一个特定的功能,为此我正在使用 NodeScheduler

我知道我可以用这个表达方式

*/3 8-15 * * *

在上午 8 点到下午 3 点之间每 3 分钟运行一次,但我想在上午 8:30 到下午 3:15 之间运行一次,但是我为此所做的 Cron 表达式肯定是错误的

30-15/3 8-15 * * *

有谁知道这种情况下正确的 cron 表达式是什么?

【问题讨论】:

    标签: cron scheduler cron-task nodejs-server node-schedule


    【解决方案1】:

    普通的cron 并没有给你那种水平的表现力,但没有什么能阻止你在条目的命令部分设置进一步的限制:

    */3 8-15 * * * [[ 1$(date +\%H\%M) -ge 10830 ]] && [[ 1$(date +\%H\%M) -le 11515 ]] && payload
    

    这实际上将在上午 8 点到下午 4 点之间每三分钟运行一次 cron 作业,但是只有在当前时间在上午 8:30 到下午 3:15 之间时才会调用有效负载(执行实际工作的脚本) .

    1 放在时间前面只是一个技巧,以避免将零开头的数字视为八进制。


    事实上,我有一个脚本withinTime.sh 证明对这类事情很有用:

    usage() {
        [[ -n "$1" ]] && echo "$1"
        echo "Usage: withinTime <hhmmStart> <hhmmEnd>"
    }
    
    validTime() {
        [[ "$1" =~ ^[0-9]{4}$ ]] || return 1  # Ensure 0000-9999.
        [[ $1 -le 2359 ]] || return 1         # Ensure 0000-2359.
        return 0
    }
    
    # Parameter checking.
    
    [[ $# -ne 2 ]] && { usage "ERROR: Not enough parameters"; exit 1; }
    validTime "$1" || { usage "ERROR: invalid hhmmStart '$1'"; exit 1; }
    validTime "$2" || { usage "ERROR: invalid hhmmEnd '$2'"; exit 1; }
    
    now="1$(date +%H%M)"
    [[ ${now} -lt 1${1} ]] && exit 1  # If before start.
    [[ ${now} -gt 1${2} ]] && exit 1  # If after end.
    
    # Within range, flag okay.
    exit 0
    

    在您的路径中使用此脚本,您可以稍微简化cron 命令:

    */3 8-15 * * * /home/pax/bin/withinTime.sh 0830 1515 && payload
    

    【讨论】:

      猜你喜欢
      • 2022-01-23
      • 1970-01-01
      • 2012-04-29
      • 1970-01-01
      • 2023-03-04
      • 1970-01-01
      • 2013-12-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多