Search code examples
cronscheduling

Cron scheduling from whole hour to half


I faced with problem. I need to set cron scheduler to start every day every minute from 8 AM to 10:30PM. Who knows, is it possible?


Solution

  • Crontab files give some form of flexibility to define periodic tasks, but in some instances, they are rigid and need some massaging to get the job done. The case presented by the OP is such as case.

    Set up a cron-job which runs every minute, every day, but do it only from time tStart up to and including tEnd

    Below you find multiple cases which allow you to perform the requested tasks in multiple intervals:

    # .----------------------- minute (0 - 59)
    # |       .--------------- hour (0 - 23)
    # |       |    .---------- day of month (1 - 31)
    # |       |    |  .------- month (1 - 12) OR jan,feb,mar,apr ...
    # |       |    |  |  .---- day of week (0 - 6) (Sunday=0 or 7)
    # |       |    |  |  |
    # *       *    *  *  *   command to be executed
    # --------------------------------------------------------------
      *    8-21    *  *  *   command1        # daily  [08:00, 21:59]
    # --------------------------------------------------------------
      *    8-21    *  *  *   command2        # daily  [08:00, 21:59]
      0      22    *  *  *   command2        # daily  [22:00, 22:00]
    # --------------------------------------------------------------
    17-59     8    *  *  *   command3        # daily  [08:17, 08:59]
      *    9-21    *  *  *   command3        # daily  [09:00, 21:59]
     0-33    22    *  *  *   command3        # daily  [22:00, 22:33]
    # --------------------------------------------------------------
      *       *    *  *  *   /path/testcmd 08:30 22:30 && command4
    

    Here, command1 will execute every minute from 08:00 up to and including 21:59. command2 is identical to command1 but the extra line also includes 22:00. command3 has a somewhat more complex form that allows a general time-frame.

    While it is possible to define complex cases using multiple lines, it makes maintenance a bit cumbersome. It is than also often useful, in case of complex cases to make use of a conditional command that allows you to perform date-time checks command4 is such a case. This command will only be executed if the command /path/testcmd 08:30 22:30 has a non-zero return-status. The testcmd could be quickly written as:

    #!/usr/bin/env bash
    tStart="$1"
    tEnd="$2"
    tNow="$(date "+%H:%M")"
    # Lexicographical comparison
    [ "$tStart" <= "$tNow" ] && [ "$tNow" <= "$tEnd" ]