MST

星途 面试题库

面试题:Bash中按指定时间间隔循环执行任务

编写一个Bash脚本,要求从当前时间开始,每隔15分钟执行一次某个命令(例如echo 'Task is running'),直到运行总时长达到2小时。请给出完整脚本代码,并解释关键部分的作用。
38.3万 热度难度
编程语言Bash

知识考点

AI 面试

面试题答案

一键面试
#!/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分钟),然后进入下一次循环。