在Linux中,Crontab任务默认是在前台运行的
使用&符号将命令放入后台运行:
在Crontab任务中,你可以在命令的末尾添加&符号,以使该命令在后台运行。例如:
* * * * * /path/to/your/script.sh &
这将使得/path/to/your/script.sh脚本在后台运行。
使用nohup命令:
nohup(no hang-up)命令可以让你的任务忽略挂起(SIGHUP)信号,从而在后台持续运行,即使你关闭了终端。例如:
* * * * * nohup /path/to/your/script.sh &
这将在后台运行/path/to/your/script.sh脚本,并且即使你关闭了终端,它也会继续运行。输出将被重定向到nohup.out文件。
使用screen或tmux:
screen和tmux是终端复用器,可以让你在一个终端窗口中运行多个终端会话。这样,你可以在一个会话中启动后台任务,然后断开连接,稍后再重新连接以检查任务的状态。例如,使用screen:
* * * * * screen -S your-session-name -d -m /path/to/your/script.sh
这将创建一个名为your-session-name的新会话,并在其中以后台模式运行/path/to/your/script.sh脚本。要重新连接会话,可以使用以下命令:
screen -r your-session-name
使用tmux的命令类似:
* * * * * tmux new-session -d -s your-session-name '/path/to/your/script.sh'
要重新连接会话,可以使用以下命令:
tmux attach-session -t your-session-name
这些方法可以帮助你在Linux Crontab任务中实现后台运行。