
nohup 命令可用于在后台运行程序,即使关闭终端或断开连接,程序仍会继续运行。然而,nohup 本身并不具备定时任务的功能。为了实现定时任务,你可以将 nohup 与 cron 或 systemd 结合使用。
结合 cron 实现定时任务
-
编辑 crontab 文件: 在终端中输入以下命令以编辑当前用户的 crontab 文件:
crontab -e
-
添加定时任务: 在 crontab 文件中添加一行,指定任务的执行时间和要运行的命令。例如,如果你希望每天凌晨 2 点运行一个名为 my_script.sh 的脚本,可以使用以下格式:
0 2 * * * nohup /path/to/my_script.sh > /path/to/output.log 2>&1 &
解释:
- 0 2 *:表示每天凌晨 2 点执行任务。
- nohup /path/to/my_script.sh:使用 nohup 运行脚本。
/path/to/output.log 2>&1:将标准输出和标准错误输出重定向到日志文件。
- &:将命令放入后台运行。
保存并退出: 保存 crontab 文件并退出编辑器。crontab 将自动加载新的配置。
结合 systemd 实现定时任务
-
创建 systemd 服务文件: 创建一个新的 systemd 服务文件,例如 /etc/systemd/system/my_service.service:
JTBC网站内容管理系统5.0.3.1下载JTBC CMS(5.0) 是一款基于PHP和MySQL的内容管理系统原生全栈开发框架,开源协议为AGPLv3,没有任何附加条款。系统可以通过命令行一键安装,源码方面不基于任何第三方框架,不使用任何脚手架,仅依赖一些常见的第三方类库如图表组件等,您只需要了解最基本的前端知识就能很敏捷的进行二次开发,同时我们对于常见的前端功能做了Web Component方式的封装,即便是您仅了解HTML/CSS也
[Unit] Description=My Scheduled Service
[Service] ExecStart=/path/to/my_script.sh Restart=always User=your_username
[Install] WantedBy=multi-user.target
-
创建 systemd 定时器文件: 创建一个新的 systemd 定时器文件,例如 /etc/systemd/system/my_timer.timer:
[Unit] Description=Run My Service every day at 2 AM
[Timer] OnCalendar=--* 02:00:00 Persistent=true
[Install] WantedBy=timers.target
-
启用并启动定时器: 启用并启动定时器:
sudo systemctl enable --now my_timer.timer
-
检查定时器状态: 检查定时器的状态:
sudo systemctl list-timers --all
通过上述步骤,你可以将 nohup 与 cron 或 systemd 结合使用来实现定时任务。选择哪种方法取决于你的具体需求和系统环境。









