面试题答案
一键面试#!/bin/bash
start_time=$(date +%s)
end_time=$((start_time + 2 * 60 * 60))
while true; do
current_time=$(date +%s)
if [ $current_time -ge $end_time ]; then
break
fi
echo 'Task is running'
sleep 15m
done
关键部分解释:
start_time=$(date +%s)
:获取当前时间的时间戳(从1970年1月1日00:00:00 UTC到现在的秒数),作为脚本开始执行的时间点。end_time=$((start_time + 2 * 60 * 60))
:计算脚本运行总时长达到2小时后的时间戳。2小时换算成秒是2 * 60 * 60
秒。while true; do
:开始一个无限循环,用于持续检查是否达到运行总时长以及执行任务。current_time=$(date +%s)
:在每次循环中获取当前时间的时间戳。if [ $current_time -ge $end_time ]; then break; fi
:判断当前时间是否达到设定的结束时间,如果达到则使用break
跳出循环。echo 'Task is running'
:执行需要每隔15分钟执行一次的命令,这里以输出文本为例。sleep 15m
:使脚本暂停15分钟(15m
表示15分钟),然后进入下一次循环。