从单个 Cron 作业执行并行脚本

从单个 Cron 作业执行并行脚本

command/script当主要任务command/script(任务 A)超出定义的时间窗口/周期时,如何以并行模式执行不同的任务(任务 B);中提到了哪一个crontab

@生产环境,没有gnome-terminal.

答案1

默认情况下会发生这种情况。计划运行全部大约在同一时间安排在给定分钟内进行的作业。没有队列,也绝对没有时间窗口/时段。只有一组开始时间。

答案2

正如 l0b0 提到的在他的回答中,crontab文件只指定作业的开始时间。它并不关心作业是否需要花费几个小时来运行,并且会在下一个开始时间到达时再次启动它,即使作业的前一个版本仍在运行。

根据您的描述,如果任务 A 运行时间太长,您似乎希望启动任务 B。

您可以通过将两个任务组合在一个同一个脚本中来实现这一目标:

#!/bin/sh

timeout=600     # time before task B is started
lockfile=$(mktemp)
trap 'rm -f "$lockfile"' EXIT INT TERM QUIT

# Start task A
# A "lock file" is created to signal that the task is still running.
# It is deleted once the task has finished.

( touch "$lockfile" && start_task_A; rm -f "$lockfile" ) &
task_A_pid="$!"

sleep 1     # allow task A to start

# If task A started, sleep and then check whether the "lock file" exists.
if [ -f "$lockfile" ]; then
    sleep "$timeout"

    if [ -f "$lockfile" ]; then
        # This is task B.
        # In this case, task B's task is to kill task A (because it's
        # been running for too long).
        kill "$task_A_pid"
    fi
fi

相关内容