3

So I have a jar file timeline.jar which when executed (using java -jar timeline.jar from its directory) saves a few JSON files in its directory.

However I need to execute timeline.jar from Crontab using:

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

and since I'm using the absolute path, the files are not saved in the jar file's directory.

Right now the only solution is to specify the exact path where to save the JSON files through the java code, but I would rather not hard code it like that.

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

Apologies if the question has been asked before, none of the answers I read seemed to answer mine. Thanks

1 Answers1

3

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

The way to specify the working directory for a cron job is to use the cd command within the job to change to the correct working directory:

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

Cron jobs are run using the shell, so you can use shell syntax within the job. The job here is a sequence of two commands, the cd command and the java command. The '&&' means that the second command (java) runs only if the first command (cd) succeeds.

In the general case, depending on the command being run you may need to set environment variables, change the working directory, or redirect standard output and standard error within the cron job. You can do all these things in shell one-liners. But personally, I try to avoid having complicated shell commands in the crontab file. If I need to do something complex in a crontab, I'll write a shell script and have cron run the script:

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

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

This is admittedly a little overkill for the case at hand. But suppose you needed to set the command PATH, and you want to capture the program's error messages in a log file, and you want to add a timestamp to the log file so you can know which run produced which errors. It's much easier to express all of these things within a shell script than directly within the crontab file:

#!/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
Kenster
  • 23,465
  • 21
  • 80
  • 106