Cron

我應該如何執行具有永遠循環的 cron 命令?

  • May 14, 2021

我有一個具有“while true”循環的腳本。而且我想每分鐘從 cron 執行該腳本,以便當程序被終止(或失敗 - 不管為什麼)時,cron 將再次執行該腳本。

但是當我檢查時,ps -aef --forest我的程序由/usr/sbin/CROND -n. 這對 cron 或系統來說不是壞事嗎?或者也許我應該做不同的事情?

也許一個systemd服務的簡短範例就可以了。

這是我們的無限腳本、位置/path/to/infinite_script、可執行位集:

#!/bin/bash
while ((1)) ; do
   date >> /tmp/infinite_date
   sleep 2
done

不,我們需要定義一個服務文件:

[Unit]
#just what it does
Description= infinite date service

[Service]
#not run by root, but by me
User=fiximan
#we assume the full service as active one the script was started
Type=simple
#where to find the executable
ExecStart=/path/to/infinite_script
#what you want: make sure it always is running
Restart=always

[Install]
#which service wants this to run - default.target is just it is loaded by default
WantedBy=default.target

並將其放入/etc/systemd/system/infinite_script.service

現在載入並啟動服務(以 root 身份):

systemctl enable infinite_script.service
systemctl start infinite_script.service

該服務現在正在執行,我們可以檢查它的狀態

systemctl status infinite_script.service

● infinite_script.service - infinite date service
  Loaded: loaded (/etc/systemd/system/infinite_script.service; enabled; vendor preset: enabled)
  Active: active (running) since Tue 2019-05-28 14:18:52 CEST; 1min 33s ago
Main PID: 7349 (infinite_script)
   Tasks: 2 (limit: 4915)
  Memory: 1.5M
  CGroup: /system.slice/infinite_script.service
          ├─7349 /bin/bash /path/to/infinite_script
          └─7457 sleep 2

Mai 28 14:18:52 <host> systemd[1]: Started infinite date service.

現在,如果您終止腳本(kill 7349- main PID)並再次檢查狀態:

● infinite_script.service - infinite date service
  Loaded: loaded (/etc/systemd/system/infinite_script.service; enabled; vendor preset: enabled)
  Active: active (running) since Tue 2019-05-28 14:22:21 CEST; 12s ago
Main PID: 7583 (infinite_script)
   Tasks: 2 (limit: 4915)
  Memory: 1.5M
  CGroup: /system.slice/infinite_script.service
          ├─7583 /bin/bash /path/to/infinite_script
          └─7606 sleep 2

Mai 28 14:22:21 <host> systemd[1]: Started infinite date service.

所以請注意它是如何使用新的 PID 立即重新啟動的。

並檢查輸出的文件所有權:

ls /tmp/infinite/date
-rw-r--r-- 1 fiximan fiximan  300 Mai 28 14:31 infinite_date

因此腳本由服務文件中設置的正確使用者執行。

當然,您可以停止和禁用該服務:

systemctl stop infinite_script.service
systemctl disable infinite_script.service

編輯:

更多細節:使用者的個人服務(預設情況下)可以$HOME/.config/systemd/user/通過systemctl --user <commands>. 就像使用個人 crontab 一樣,不需要 root。

引用自:https://unix.stackexchange.com/questions/521497