可以同时运行 cron 作业吗?

yae*_*ael 5 linux cron rhel shell-script

我们想在午夜的同一时间删除以下作业的所有文件

0 0 * * * root  [[ -d /var/log/ambari-metrics-collector ]] && find  /var/log/ambari-metrics-collector  -type f -mtime +10 -regex '.*\.log.*[0-9]$' -delete 

0 0 * * * root  [[ -d /var/log/kO ]] && find  /var/log/Ko  -type f -mtime +10 -regex '.*\.log.*[0-9]$' -delete 

0 0 * * * root  [[ -d /var/log/POE ]] && find  /var/log/POE  -type f -mtime +10 -regex '.*\.log.*[0-9]$' -delete  

0 0 * * * root  [[ -d /var/log/REW ]] && find  /var/log/REW  -type f -mtime +10 -regex '.*\.log.*[0-9]$' -delete 
Run Code Online (Sandbox Code Playgroud)

可以同时运行吗?

剂量 cron 工作会逐步运行它们吗?或者他们都在同一个线程上?

Dop*_*oti 5

是的,同时cron安排多个作业是完全可以接受的。

但是,计算机同时不执行任何操作,它们将按照cron表中显示的顺序启动。但是,它们不会按顺序运行;它们将在午夜的几毫秒内一个接一个地启动 -- 同时出于所有实际目的。

  • 一般来说,情况可能如此。但实际上,在同一个 FS 中运行 4 个并行“find”-s 或任何其他 IO 密集型程序并不是最明智的想法。根据 FS,可能会显着改变性能并引入 iowait。 (2认同)

Kus*_*nda 5

Cron 将几乎同时启动所有作业,并且它们将同时执行。

不过,对于此类清理作业,最好编写一个简短的 shell 脚本以按顺序运行该过程。这将防止多次find运行彼此减慢速度(并使系统其余部分的磁盘访问可能有点缓慢)。它还可以轻松更改/更新清理程序(例如,添加新目录或修改find条件等),而无需修改其 cron 规范(或添加更多清理作业)。

例如,

#!/bin/bash

for dir in /var/log/{ambari-metrics-collector,k0,POE,REW}; do
    [ ! -d "$dir" ] && continue
    find  "$dir" -type f -mtime +10 -regex '.*\.log.*[0-9]$' -delete
done
Run Code Online (Sandbox Code Playgroud)

要不就

#!/bin/bash

find  /var/log/{ambari-metrics-collector,k0,POE,REW} -type f -mtime +10 -regex '.*\.log.*[0-9]$' -delete
Run Code Online (Sandbox Code Playgroud)

(如果这些目录中的一个或几个不存在,这也会产生错误,这可能有用也可能没有用)

然后,您将使用 cron 以适合您系统的任何方式安排此脚本的运行。


稍微发烧友:

#!/bin/bash

# directories to clean up
dirs=( /var/log/ambari-metrics-collector
       /var/log/k0
       /var/log/POE
       /var/log/REW
)

for dir in "${dirs[@]}"; do
    if [ ! -d "$dir" ]; then
        printf 'Dir "%s" does not exist, check this!\n' "$dir" >&2
    else
        printf 'Removing files from "%s":\n' "$dir"
        find  "$dir" -type f -mtime +10 -regex '.*\.log.*[0-9]$' -print -delete
    fi
done
Run Code Online (Sandbox Code Playgroud)

或者,完全放弃这种方法并使用logrotate或类似的软件,并正确地进行日志文件维护。