问题描述
我正在尝试创建一个脚本,该脚本将比较cron,如果当前日期/时间在cron开始/停止时间之内,则执行功能。如果只有一个cron条目用于启动/停止,这很简单,但是我不知道如何允许多个cron。我正在使用posix / ash,但是如果有人可以提供bash示例,希望我可以适应它。我只是坚持了解如何构造逻辑?
例如:如果cron是这个,那将是一个简单的if
语句:
00 09 * * Mon,Tue,Wed,Thu,Fri,Sat,Sun /usr/bin/wifi_schedule.sh start
00 11 * * Mon,Sun /usr/bin/wifi_schedule.sh stop
但是,如果有多个分支,我不确定该如何处理:
00 09 * * Mon,Sun /usr/bin/wifi_schedule.sh stop
00 15 * * Mon,Sun /usr/bin/wifi_schedule.sh start
00 17 * * Mon,Sun /usr/bin/wifi_schedule.sh stop
00 19 * * Mon,Sun /usr/bin/wifi_schedule.sh start
00 21 * * Mon,Sun /usr/bin/wifi_schedule.sh stop
我尝试使用while
,但这似乎只会影响第一个比赛或进入循环。
我要执行的操作是,如果它与cron匹配,则调用启动无线功能。例如,如果设备在cron启动时间之后和cron停止时间之前启动,则启动无线功能;如果设备在cron停止之后启动,则停止无线功能。到目前为止,我尝试过的一些事情是:
获取当前的$day
和$hour
day=$(date +%a) & hour=$(date +%H)
获得$start
的cron $stop
和$day
次
start=$(grep $day /etc/crontabs/root | awk '/start/ {print $2}')
stop=$(grep $day /etc/crontabs/root | awk '/stop/ {print $2}')
计算开始/停止时间(例如$count=3
)
count=$(echo "$start" | wc -l)
创建用于启动/停止的变量
set -- $start
set -- $stop
从$count=3
确定变量(例如-$3
,$2
,$1
)
var=$(eval echo \$$count)
我使用while
的失败示例:
while [ $var -le $hour ];
do
if [ $hour -ge $var ]; then
echo "do something"
else
var=$(eval echo \$$count)
count=$(( $count - 1 ))
echo "do something else"
fi
done
exit
任何对此的指导将不胜感激,谢谢。
解决方法
解析crontabs来确定某项工作是否应该运行对我来说根本上是错误的。
如果另一个 crontab运行同一组脚本怎么办?
如果脚本是手动运行的怎么办?
如果将cron逻辑切换为systemd.timers
怎么办?
您似乎真正想做的是检查系统是否处于给定状态(例如“ WiFi已打开”或什至“ WiFi应该已打开”)。
所以您真正应该做的是尝试找出系统是否处于请求状态。
就像在cron执行的脚本中设置标志一样简单。
例如您的wifi_schedule.sh
脚本(您应该将其放入/usr/local/bin/
中,因为/usr/bin
是为系统保留的):
#!/bin/sh
case "$1" in
start)
echo 1 > /var/run/wifi_schedule
;;
stop)
echo 0 > /var/run/wifi_schedule
;;
esac
# here comes the actual script:
# ...
如果实际的实际任务比较复杂,您可以考虑从cron
切换到systemd.unit
(显然只有在systemd可以接受的情况下),这可以使您表达时间,执行顺序及其各部分之间的依赖关系。