在Debian中,你可以使用nohup
命令结合cron
来实现定时任务
打开终端。
输入crontab -e
命令来编辑当前用户的cron
任务列表。如果你想为其他用户设置定时任务,请使用sudo crontab -u username -e
。
在打开的编辑器中,添加一行新的cron
任务。cron
任务的格式如下:
* * * * * command-to-be-executed
- - - - -
| | | | |
| | | | ----- Day of week (0 - 7) (Sunday to Saturday; 7 is also Sunday)
| | | ------- Month (1 - 12)
| | --------- Day of month (1 - 31)
| ----------- Hour (0 - 23)
------------- Minute (0 - 59)
例如,如果你想每天凌晨1点运行一个名为my_script.sh
的脚本,你可以添加以下行:
0 1 * * * nohup /path/to/your/script/my_script.sh > /dev/null 2>&1 &
这里,nohup
命令确保即使关闭终端,脚本也会继续运行。> /dev/null 2>&1
将标准输出和错误输出重定向到/dev/null
,以避免产生不必要的日志。最后的&
符号让脚本在后台运行。
cron
将自动加载新的任务列表。注意:在使用nohup
时,请确保你的脚本具有可执行权限。你可以使用chmod +x /path/to/your/script/my_script.sh
命令为脚本添加可执行权限。