How can I set cron to run certain commands every one and a half hours?

前端 未结 9 1381
走了就别回头了
走了就别回头了 2020-11-27 18:42

How can I set cron to run certain commands every one and a half hours?

9条回答
  •  隐瞒了意图╮
    2020-11-27 19:00

    You can achieve any frequency if you count the minutes(, hours, days, or weeks) since Epoch, add a condition to the top of your script, and set the script to run every minute on your crontab:

    #!/bin/bash
    
    minutesSinceEpoch=$(($(date +'%s / 60')))
    
    # every 90 minutes (one and a half hours)
    if [[ $(($minutesSinceEpoch % 90)) -ne 0 ]]; then
        exit 0
    fi
    

    date(1) returns current date, we format it as seconds since Epoch (%s) and then we do basic maths:

    # .---------------------- bash command substitution
    # |.--------------------- bash arithmetic expansion
    # || .------------------- bash command substitution
    # || |  .---------------- date command
    # || |  |   .------------ FORMAT argument
    # || |  |   |      .----- formula to calculate minutes/hours/days/etc is included into the format string passed to date command
    # || |  |   |      |
    # ** *  *   *      * 
      $(($(date +'%s / 60')))
    # * *  ---------------
    # | |        | 
    # | |        ·----------- date should result in something like "1438390397 / 60"
    # | ·-------------------- it gets evaluated as an expression. (the maths)
    # ·---------------------- and we can store it
    

    And you may use this approach with hourly, daily, or monthly cron jobs:

    #!/bin/bash
    # We can get the
    
    minutes=$(($(date +'%s / 60')))
    hours=$(($(date +'%s / 60 / 60')))
    days=$(($(date +'%s / 60 / 60 / 24')))
    weeks=$(($(date +'%s / 60 / 60 / 24 / 7')))
    
    # or even
    
    moons=$(($(date +'%s / 60 / 60 / 24 / 656')))
    
    # passed since Epoch and define a frequency
    # let's say, every 7 hours
    
    if [[ $(($hours % 7)) -ne 0 ]]; then
        exit 0
    fi
    
    # and your actual script starts here
    

提交回复
热议问题