运行 来自终端的 jar 文件使用绝对路径

Running jar files from terminal using absolute path

所以我有一个 jar 文件 timeline.jar 执行时(使用其目录中的 java -jar timeline.jar)会在其目录中保存几个 JSON 文件。

但是我需要使用以下命令从 Crontab 执行 timeline.jar

5 * * * * java -jar /path/to/timeline.jar

因为我使用的是绝对路径,所以文件不会保存在 jar 文件的目录中。

现在唯一的解决办法是通过java代码指定保存JSON文件的确切路径,但我不想那样硬编码。

肯定有办法从 Crontab 命令中指定 "current directory" 吗?

抱歉,如果之前有人问过这个问题,none 我阅读的答案似乎回答了我的问题。谢谢

Surely there must be a way to specify the "current directory" from the Crontab command?

为 cron 作业指定工作目录的方法是在作业中使用 cd 命令更改到正确的工作目录:

5 * * * * cd /path/to && java -jar timeline.jar

Cron 作业 运行 使用 shell,因此您可以在作业中使用 shell 语法。这里的作业是两个命令的序列,cd 命令和 java 命令。 '&&' 表示仅当第一个命令 (cd) 成功时,第二个命令 (java) 运行s。

在一般情况下,根据命令 运行,您可能需要设置环境变量、更改工作目录或在 cron 作业中重定向标准输出和标准错误。您可以在 shell 一行中完成所有这些事情。但就个人而言,我尽量避免在 crontab 文件中使用复杂的 shell 命令。如果我需要在 crontab 中做一些复杂的事情,我会写一个 shell 脚本并让 cron 运行 脚本:

#!/bin/bash
cd /path/to && java -jar timeline.jar

...
5 * * * * /home/jdoe/bin/launch-timeline-jar.sh

诚然,对于手头的案例来说,这有点矫枉过正。但是假设您需要设置命令 PATH,并且您想要在日志文件中捕获程序的错误消息,并且您想要向日志文件添加时间戳以便您可以知道哪个 运行 产生了哪些错误。在 shell 脚本中表达所有这些东西比直接在 crontab 文件中表达要容易得多:

#!/bin/bash

PATH=/some/path/bin:${PATH}      # Set our PATH
cd /path/to || exit 1            # Set the working directory
exec >> timeline.log 2>&1        # Direct output to a logfile
date                             # Write a timestamp to the log
exec java -jar timeline.jar      # Launch the command we came here for