nohup
命令本身并不提供定時任務的功能,它的主要作用是讓進程忽略掛起(SIGHUP)信號,從而在用戶退出登錄后繼續運行
cron
定時任務:編輯用戶的 crontab
文件,添加一行定時任務。例如,如果你想每天的 1:00 運行一個名為 your_script.sh
的腳本,可以這樣做:
crontab -e
然后在打開的文件中添加以下內容:
0 1 * * * nohup /path/to/your_script.sh > /path/to/output.log 2>&1 &
保存并退出編輯器。這樣,你的腳本將每天 1:00 在后臺運行,并且不受掛起信號的影響。
systemd
定時任務:創建一個新的 systemd
服務單元文件,例如 /etc/systemd/system/your_service.service
,并添加以下內容:
[Unit]
Description=Your custom service
[Service]
ExecStart=/path/to/your_script.sh
Restart=always
User=username
Environment=PATH=/usr/bin:/usr/local/bin
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=your_service
[Install]
WantedBy=multi-user.target
然后創建一個 systemd
定時器單元文件,例如 /etc/systemd/system/your_service.timer
,并添加以下內容:
[Unit]
Description=Run your_service.service every day at 1:00 AM
[Timer]
OnCalendar=*-*-* 01:00:00
Persistent=true
Unit=your_service.service
[Install]
WantedBy=timers.target
啟用并啟動定時器:
sudo systemctl enable --now your_service.timer
這樣,你的腳本將每天 1:00 在后臺運行,并且不受掛起信號的影響。