在Debian系统中,你可以使用nohup
命令结合cron
来实现定时任务
打开终端。
输入crontab -e
命令来编辑当前用户的cron
任务表。如果你想为其他用户设置定时任务,请使用sudo crontab -e -u username
,将username
替换为目标用户的用户名。
在打开的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/your_username/scripts/
目录下,你可以在cron
任务表中添加以下行:
0 1 * * * nohup /home/your_username/scripts/my_script.sh >/dev/null 2>&1 &
这里的nohup
命令确保脚本在后台运行,即使你关闭终端也不会中断。>/dev/null 2>&1
将标准输出和错误输出重定向到/dev/null
,这样你就不会收到关于脚本输出的电子邮件。最后的&
符号让脚本在后台运行。
crontab -l
命令查看当前用户的定时任务列表。注意:确保你的脚本具有可执行权限。如果没有,你可以使用chmod +x /home/your_username/scripts/my_script.sh
命令为脚本添加可执行权限。