在 CentOS 系统中,你可以结合 nohup 命令和 cron 来实现定时任务
打开终端。
输入 crontab -e 命令来编辑当前用户的 crontab 文件。如果你想编辑其他用户的 crontab 文件,请使用 sudo crontab -e -u username,其中 username 是目标用户的用户名。
在打开的 crontab 文件中,按照 cron 的语法添加一行定时任务。cron 的语法格式如下:
* * * * * command-to-be-executed
- - - - -
| | | | |
| | | | ----- Day of the week (0 - 7) (Sunday to Saturday; 7 is also Sunday)
| | | ------- Month (1 - 12)
| | --------- Day of the month (1 - 31)
| ----------- Hour (0 - 23)
------------- Minute (0 - 59)
例如,如果你想每天凌晨 1 点运行一个名为 my_script.sh 的脚本,该脚本位于 /home/username/scripts/ 目录下,你可以添加以下行:
0 1 * * * nohup /home/username/scripts/my_script.sh > /dev/null 2>&1 &
这里,nohup 命令用于在后台运行脚本,即使关闭终端也不会中断。> /dev/null 2>&1 将脚本的输出重定向到 /dev/null,即丢弃输出。最后的 & 符号表示将命令放入后台运行。
现在,你的定时任务已经设置好了。你可以使用 crontab -l 命令查看当前用户的定时任务列表。如果你想查看其他用户的定时任务,请使用 sudo crontab -l -u username。