nohup
命令本身不提供定时任务的功能,它主要用于在后台运行程序,使程序在用户退出登录后继续运行
cron
定时任务:编辑用户的 crontab
文件,添加一行定时任务。例如,如果你想每天的 1:00 运行一个名为 your_script.sh
的脚本,可以这样做:
crontab -e
然后在打开的编辑器中添加以下内容:
0 1 * * * nohup /path/to/your_script.sh > /path/to/output.log 2>&1 &
保存并退出编辑器。这样,nohup
命令就会在每天的 1:00 运行 your_script.sh
脚本,并将输出重定向到 output.log
文件。
systemd
定时任务(适用于 systemd):创建一个新的 systemd
定时器单元文件,例如 your_timer.timer
:
[Unit]
Description=Run your script every day at 1:00 AM
[Timer]
OnCalendar=*-*-* 01:00:00
Persistent=true
[Install]
WantedBy=timers.target
创建一个新的 systemd
服务单元文件,例如 your_service.service
:
[Unit]
Description=Your script service
[Service]
ExecStart=/path/to/your_script.sh
将这两个文件保存到 /etc/systemd/system/
目录下。然后运行以下命令启用并启动定时器:
sudo systemctl enable --now your_timer.timer
这样,nohup
命令就会在每天的 1:00 运行 your_script.sh
脚本,并将输出重定向到日志文件(默认为 /var/log/syslog
)。