Shell: SetWakeUpTime

De TheNets Wiki
Ir para: navegação, pesquisa

Define uma hora para um script em loop infinito acordar.

 1 #!/bin/bash
 2 
 3 # Set time to wakeup
 4 # 0-23 hours format
 5 # 0-59 minutes format
 6 WAKEUP_HOUR=23
 7 WAKEUP_MINUTES=00
 8 
 9 # Stop script if get error
10 set -e
11 
12 # Validation
13 hour=${WAKEUP_HOUR}
14 if [ $hour -gt 23 ] || [ ! $hour -gt 0 ]; then
15         echo "Error: \$hour=${hour} allowed between 0-23" 2>&1
16         exit 1
17 fi
18 minute=${WAKEUP_MINUTES}
19 if [ $minute -gt 59 ] || [ ! $minute -gt 0 ]; then
20         echo "Error: \$minute=${minute} allowed between 0-59" 2>&1
21         exit 1
22 fi
23 
24 # Calculate times
25 currentDate=$(date --date "$(date +%Y-%m-%d) $(date +%H:%M:%S)" +%s)
26 nextDate=$((${currentDate}+86400))
27 nextDateFormated=$(printf '%(%Y-%m-%d)T\n' "$nextDate")
28 scheduleDate=$(date --date "$(date --date ${nextDateFormated} +%Y-%m-%d) ${hour}:${minute}:00" +%s)
29 timeToSleep=$(expr $((scheduleDate-currentDate)) % 86400)
30 
31 # DEBUG
32 #echo 'Current          : '${currentDate}
33 #echo 'Next             : '${nextDate}
34 #echo 'Schedule         : '${scheduleDate}
35 #echo 'ScheduleFormated : '$(printf '%(%Y-%m-%d %H:%M:%S)T\n' "$scheduleDate")
36 #echo 'Delta            : '$((scheduleDate-currentDate))
37 #echo 'TimeToSleep      : '${timeToSleep}
38 
39 # Output
40 sleep ${timeToSleep}
41 echo 'Will wake-up at  : '$(printf '%(%Y-%m-%d %H:%M:%S)T\n' "$scheduleDate")