[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: Cron Jobs and Time Zones Has Anything Changed?

On Wed, Dec 02, 2020 at 01:17:02PM -0500, Dan Ritter wrote:
> As a name for the utility, I suggest "do-if-time-in" and require
> three parameters:
> do-if-time-in timezone time "command"
> As an interim fix, though: (and I know Greg's going to fix this)
> ---
> #!/bin/bash
> TZ=$1
> NOW=$(date +%H%M)
> echo $NOW
> if [ "$2" = "$NOW" ]  ;
>     then echo $("$3")
> fi 
> ---

There are two natural designs for a utility like this.  The first would
take three inputs (time zone, start time, end time), and return an exit
status that says whether the current time is within the interval.

The second design would take those same inputs, plus a command to execute
if and only if the current time is within the interval.  For that design,
you'd use chain-loading (exec).

In either case, you don't need to pass the time zone as a parameter.  You
can just use the TZ environment variable.

The real problem is how you specify the start and end times.  In your
sample code, the result of the date command is HHMM format, so your
parameters would have to be given that way as well.  HHMM may not be
the more useful format, especially since it doesn't give you a way to
specify a date.

For the purposes of this email, as an exercise, let's say we decide
to specify the start and end times in HH:MM format, and skip the whole
notion of specifying a date.  That makes it reasonably easy to


usage() {
    echo "usage: $0 starttime endtime command [args]"
    echo "starttime and endtime must be in HH:MM format"

if (($# < 3)); then
  usage >&2
  exit 1

start=$1 end=$2
shift 2

if [[ $start != [0-9][0-9]:[0-9][0-9] || $end != [0-9][0-9]:[0-9][0-9] ]]; then
  usage >&2
  exit 1

printf -v now '%(%H:%M)T' -1
if [[ $now >= $start && $now <= $end ]]; then
  exec "$@"

I didn't do anything with TZ because it's not *necessary*.  If it's
given as an environment variable, it'll take hold automatically.  If
it's not given, then the system's default time zone will be used.

Reply to: