1

I have some logic for executing java projects; it all works in the terminal console when I type it, but not in the cron scheduler:

run 1st microservice and get variable from POST request:

java -jar /root/parser-0.0.1-SNAPSHOT.jar
value=$(curl -d '{"query":"java-middle", "turnOff":true}' -H "Content-Type: application/json" -X POST http://localhost:8080/explorer)
v2=$(echo ${value} | jq '.id')

test:

echo $v2
18

18 - id from database, and I use it in next request: (first run new microservice)

java -jar parsdescription-0.0.1-SNAPSHOT.jar 
value=$(curl -d '{"explorerId":'$v2', "turnOff":true}' -H "Content-Type: application/json" -X POST http://localhost:8080/descriptions) >> /var/log/description3.log 2>&1

So, curl executed normal, database did fill some data and in value I get correct value.

But, when I create a crontab schedule:

50 09 * * * java -jar /root/parser-0.0.1-SNAPSHOT.jar
51 09 * * * value=$(curl -d '{"query":"java-middle", "turnOff":true}' -H "Content-Type: application/json" -X POST http://localhost:8080/explorer)
52 09 * * * v2=$(echo ${value} | jq '.id')
53 09 * * * java -jar parsdescription-0.0.1-SNAPSHOT.jar 
54 09 * * * value=$(curl -d '{"explorerId":'$v2', "turnOff":true}' -H "Content-Type: application/json" -X POST http://localhost:8080/descriptions) >> /var/log/description3.log 2>&1

Then execute normally only first curl (in database created new note). In next - executed second microservice ( 53 09 * * * java -jar parsdescription-0.0.1-SNAPSHOT.jar ), but nothing not execute in second curl command, and nothing save in description3.log file - he is a empty.

Why that worked in console, but not working in crontab?

1 Answer 1

5

Each cron job is a unique shell instance that does not share state with any other cron job, so

51 09 * * * value=42

sets value only for that job, which then exits, and value is then lost. A shell session, by contrast, maintains state over successive lines. You will need a single cron job that runs all that code, or some other design; a single cron job might look like

51 09 * * * /path/to/your/script

and then the file /path/to/your/script should be executable and contain

#!/bin/bash
java -jar /root/parser-0.0.1-SNAPSHOT.jar
value=$(curl -d '{"query":"java-middle", ...

and so forth.

If you need to share data between different cron jobs that information would need to be shared via some IPC (interprocess communication) method (the filesystem, a database, etc).

2
  • Can I use a bash script for this? Sep 5, 2018 at 13:47
  • 1
    @ВалерійГрузицький yes, you can run a shell script from cron. Unless you really need the minute delay, just use one cron entry to run a shell script with all of it. (Or if you need the minute delay, add some sleep 60 in the shell script)
    – derobert
    Sep 5, 2018 at 13:51

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .