最新项目中需要用到定时任务,我使用宝塔面板的计划任务,我发现 我手动成功启动java项目的脚本 在 crontab里 不生效,不生效的原因 就是不认识java命令,fail to run command java 这样。
网上找了一下,很多,但是给我最直接的启发就是这篇http://linuxshellaccount.blogspot.com/2007/10/crontab-and-your-environment.html
Hey There,
This is a question that gets asked by everyone, at some point or another. My script works fine when I run it at the command line, but it never executes correctly when I run it in cron. Why not?
This usually boils down to a few reasons:
1. The cron entry is vague (Cron, at least in the old days) used to be very strict. That is, it ran in a totally different environment than the environment the user had while logged into the shell. It's always good practice to type
* * * * * /usr/bin/ls
rather than
* * * * * ls
2. That same rule applies for the inside of your scripts. Absolute paths to executables should be used as opposed to just the names of the executables (excluding shell built-ins, of course). So, again:
/bin/grep
rather than
grep
说了半天 ,也就是所谓的Absolute paths to executables should be used,就是 要用到绝对路径
java -jar XXXXX.jar就要改成 java bin目录的java的绝对路径 -jar XXXXX.jar这样
原来我启动 springboot项目是这样的脚本:
nohup java -XX:+UseG1GC -jar imapi-*.war --spring.config.location=./application.properties > /dev/null 2>&1 &
while( [ ! -e logs/log.log ] )
do
echo 'Wait for the log file to be generated...'
/usr/bin/sleep 1
done
tail -f logs/log.log
注意 第一行的 java , 还有-jar后面的war包, 还有 location后面的 外置配置文件,都要写成绝对路径
例如我的java路径是/opt/java/jdk1.8.0_131/bin
imapi-*.war的路径是/opt/spring-boot-imapi
./application.properties的路径是 /opt/spring-boot-imapi
启动脚本就应该是:
#!/bin/bash
nohup /opt/java/jdk1.8.0_131/bin/java -XX:+UseG1GC -jar /opt/spring-boot-imapi/imapi-*.war --spring.config.location=/opt/spring-boot-imapi/application.properties > /dev/null 2>&1 &
while( [ ! -e ./logs/log.log ] )
do
echo 'Wait for the log file to be generated...'
/usr/bin/sleep 1
done
tail -f logs/log.log
启动脚本要封装一下 后面的 logs没用绝对路径也是不对的 但是 不影响项目启动