linux

nohup命令在Linux中如何实现定时任务

小樊
41
2025-09-24 16:14:14
栏目: 智能运维

nohup 命令本身并不提供定时任务的功能,它的主要作用是让进程忽略挂起(SIGHUP)信号,从而在用户退出登录后继续运行

  1. 使用 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 在后台运行,并且不受挂起信号的影响。

  1. 使用 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 在后台运行,并且不受挂起信号的影响。

0
看了该问题的人还看了