Cron job not running the jar - java

This is my Java file for which I have created Delete.jar
import java.io.*;
public class Delete {
public static void main(String[] args)
{
try{
int i =1;
while(i<5){
File directory = new File("downloads");
System.out.println("I am running");
for(File file: directory.listFiles()) file.delete();
i++;
}
}catch(Exception e){
e.printStackTrace();
}
}
}
This is my Script to run the jar file if it is not running
#!/bin/bash
processid=`pgrep -f 'Delete.jar high'`
echo "Processes:"$processid
if [ -n "$processid" ]
then
echo "Process is running. No action will be taken"
else
echo "Process is not running. Executing ResponseHandler-fast now !"
cd /home/ubuntu/;
java -jar Delete.jar high
fi
This is line I have added to my crontab -e
* * * * * sh /home/ubuntu/check.sh
I rebooted my System I was expecting that my script will run check that jar is not running and it will run it but it is not doing so.
What I am doing wrong here.
If I execute ps after 2 -3 minutes still I am not getting java as an entry.
Thanks.

Please send output of your shell script to a log file as shown below(make changes to your crontab entry):
* * * * * sh /home/ubuntu/check.sh >> /home/ubuntu/output.log 2>&1
In this way, you will know what exactly is being run and then finding the exact cause will become easier.

Cron doesn't magically make the program "run forever". Start the program manually. It will probably take 1-2 seconds to run, then exit. This is exactly what happens when running with cron, as well. So, unless you run ps the second your program gets started, you won't see anything in the process list.
Your loop 1..5 won't help, as after the files are deleted in the first round, the rest is effectively a no-op.

Did you try running /home/ubuntu/check.sh manually? May be it's not finding the jar file or even java program.

Related

Start jar file with TimerTask schedule in background in linux

I am trying to run my application from a jar file in background. I've already tried nohup and & but they don't work.
nohup java -cp ~/DataGenerator/target/GenerateDataApp-1.0-SNAPSHOT.jar Generator.App -p ~/Text2.txt &
My application is a simple timer that runs every 1s, generating a random number every time and saving it to a file.
public class App {
public static void main(String[] args) throws Exception{
System.out.println("Start");
Arguments arguments = Arguments.fromMain(args);
SaveToFile saveToFile = new SaveToFile();
saveToFile.creatFile(arguments.getPathToPropertiesFile());
Timer timer = new Timer();
timer.schedule(new SaveFileRunner(arguments), 0, 100);
}
}
I also tried the bash script, but it didn't help either.
#!/bin/sh
cd ~/DataGenerator/target
java -cp ~/DataGenerator/target/GenerateDataApp-1.0-SNAPSHOT.jar Generator.App -p ~/Text.txt
Could someone advise me how can I make a timer work in the backend?
To make a program run as a background job, add & to the end of the command line. For example:
java ...parameters here... &
A possible problem with this is if the program writes output, that is still displayed in the terminal. You can send that output to a file.
java ...parameters here... >output.txt 2>&1 &
A second problem is that if you close the shell or logout, the program is stopped. To avoid that, use nohup.
nohup java ...parameters here... >output.txt 2>&1 &

python - JAR works in terminal but not from python

I working on a python 3 script for doing some bench (school purpose). So I need to invoke my JAR.
I use subprocess.check_output for that.
java_out = subprocess.check_output("java -jar my_jar.jar -p input_file", shell=True)
In terminal it works fine, I get the expected output and exit code is 0.
But in python, I get this :
Syntax error. (One of my java exception, but it might not happen in this case)
Traceback (most recent call last):
File "C:/Users/Jeremy/PycharmProjects/bench_bf/bench_script.py", line 41, in <module>
main()
File "C:/Users/Jeremy/PycharmProjects/bench_bf/bench_script.py", line 32, in main
result_list.append(bench(bf_file, stats_file))
File "C:/Users/Jeremy/PycharmProjects/bench_bf/bench_script.py", line 10, in bench
java_out = subprocess.check_output("java -jar my_jar.jar -p input_file", shell=True)
File "C:\Python34\lib\subprocess.py", line 620, in check_output
raise CalledProcessError(retcode, process.args, output=output)
subprocess.CalledProcessError: Command 'java -jar my_jar.jar -p input_file' returned non-zero exit status 5
Process finished with exit code 1
That does not make any sense to me. Can anyone help me ? Thanks !
The full code is following (I've also tried with absolute path) :)
import subprocess
import os
import re
FILE_NAME = "input_file"
JAR_NAME = "my_jar.jar"
TEST_ITER = 5
def bench(bf_file, stats_file):
java_out = subprocess.check_output("java -jar "+ JAR_NAME + " -p " + FILE_NAME, shell=True)
print(java_out)
m = re.search(".*EXEC_TIME : (\d*) ms.*EXEC_MOVE : (\d*)", java_out)
return [m.group(0), m.group(1)]
def init_stats(f):
f.write("Iterations; Exec time; exec move")
def write_file(f):
f.write("+++")
def main():
bf_file = open(FILE_NAME, "w", encoding="utf-8")
stats_file = open("bench-result.csv", "w")
write_file(bf_file)
init_stats(stats_file);
result_list = []
for i in range(0,TEST_ITER):
result_list.append(bench(bf_file, stats_file))
average_time = 0;
for res in result_list:
average_time += res[0]
average_time /= TEST_ITER;
stats_file.write(average_time + ";" + result_list[0][1])
main()
EDIT: I also tried java_out = subprocess.check_output(["java", "-jar", "my_jar.jar", "-p", "input_file"], shell=True), it changes nothing.
EDIT 2: Same result using absolute path or os.system
* SOLUTION *
Since I open the file in write mode, my JAR can't open it, and consider it's empty... Thanks my mate DjNikita :)
My first thought would be that there is something in your environment that is not transferring to the subprocess. Try this and see if it outputs anything that looks relevant
import os
for key in os.environ:
if any(token in key.lower() for token in ['java', 'jre', 'jdk']):
print(key, os.environ[key])
I've had another thought too. Some programs expect their input to be a tty (ie. interactive terminal) and get angry when they're fed in a pipe. Is there anything in your Java program that might cause it to expect a certain type of input stream?
Try specifying the absolute path of the jar file, as it might be that your sub-process isn't running the directory you think it is.
Try running 'dir' and seeing where it returns, for instance. Maybe check that 'java --V' (the version flag? not in a position to check at the moment) returns something indicating that Java ran, rather than an error. Basically, try and get a simple thing running via Python, then extend it.

How do I kill a specific java file after one hour, without knowing it's specific PID?

Currently my batch file will launch 20 jars with different arguments, after an hour, a taskkill command kills all java, the batch file will now launch 20 different jars.
My problem is, max cpu usage on startup, and potentially wasted cpu later. I could start the jar files at different times, but then they won't run for equal amounts of time. Takes up to 5 minutes for the cpu usage to half.
I need to launch a jar file, then kill it in an hour, without touching the other 19 jar files, and without knowing the PID.
I have been browsing the web and I see some stuff about, making it a background process, then getting the PID that way, can someone help me out with that?
This is what it looks like now
java -jar file.jar -a first
timeout 3
java -jar file.jar -a second
timeout 3
java -jar file.jar -a third
timeout 3
Use jps.exe utility (which is part of standard JDK) to learn the PID of the just started Java process. Then use taskkill /pid to kill this one process.
I'm just going to have some fun here :)
If you don't have ownership of the jars you might try something like:
public class KillTask extends TimerTask {
private Process process;
public KillTask(Process process) {
this.process = process;
}
#Override
public void run() {
// Prepare to die!
process.destroy();
}
}
public class KillDriver {
public KillDriver(String command) {
try {
Process process = Runtime.getRuntime().exec(command);
new Timer().schedule(new KillTask(process), 60 * 60 * 1000);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
for (String s : args)
new KillDriver(s);
}
}
This example assumes multiple jars will be started but you can alter that for a single or possibly pass in the delay as an argument to add some flexibility.
It appears you are giving the Jars their own process names ("first", "second", "third"), so I assume you could use a VBscript like this that does not require the PID to kill it.
ProcessName = "FIRST"
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate,authenticationLevel=pktPrivacy,(Debug)}!\\.\root\cimv2")
Set colProcessList = objWMIService.ExecQuery("Select * From Win32_Process")
For Each objProcess in colProcessList
If InStr(UCase(objProcess.Name), ProcessName) Then
WScript.Echo "Killing " & objProcess.Name
objProcess.Terminate()
End If
Next

How can I use Powershell's ExitCode to restart a Client/Server pair that I shut down?

I have a simple Java client-server application (code linked on previous Stack question here), that I can run all together with the following Powershell code:
Start-Process java "-cp .;.\lib\commons-io-2.4.jar FixedMessageSequenceServer"
Start-Sleep -Seconds 1
$JavaClient = Start-Process java "-cp .;.\lib\commons-io-2.4.jar FixedMessageSequenceClient -Wait -PassThru"
This works fine. However, I want to add either Powershell code or Java code that would restart the above Powershell code if we force shutdown ( by CTRL-C ) the application (from the Server-side).
I thought that I should be apple to use this code :
if($JavaClient.ExitCode)
{
# exit code is non-zero, better retry
Start-Process java "-cp .;.\lib\commons-io-2.4.jar FixedMessageSequenceServer" -Wait
Start-Process java "-cp .;.\lib\commons-io-2.4.jar FixedMessageSequenceClient -Wait -PassThru"
}
However this does not do anything when I run it. Would I need to append some Java ProcessBuilder code to achieve desired functionality ? Do we need to do processing of the $JavaClient.ExitCode ?
thanks
If you're only evaluating on a single if statement you have a small window for when it can restart even if that code you have did work.
I suggest you create a small polling script that will check the status of a certain process every 10 seconds, 1 minute, etc. and if it isn't running it can start it that way. You could nest this in an infinite loop if the java client should be running at all times, or you could use scheduled tasks to kick off the script if it should be running at a consistent interval/trigger (i.e. top of every hour, etc.)
Try something like this:
if(![bool](get-process java -ErrorAction SilentlyContinue)){
start-process java "-cp .;.\lib\commons-io-2.4.jar FixedMessageSequenceClient -Wait -PassThru"
}
The following code I have works, but it's not very graceful way of doing it:
This is my Java class :
import java.io.*;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class FixedMessageRunner{
public static void main(String[] args) {
// File file = new File("C://Java_Scratch_//Autonomic_Using_Batch//someFile.txt" );
try {
/* StackOverflow code */
for ( ; ; ) {
ProcessBuilder pb = new ProcessBuilder("Powershell ", "WindowsTaskSchedulerPS.PS1");
pb.directory(new File("C://Java_Scratch3_new_cleaned_Mar12//"));
Process p = pb.start();
p.waitFor();
}
/* end - StackOverflow code */
}
catch (IOException i) {
i.printStackTrace();
}
catch (InterruptedException i) {
i.printStackTrace();
}
// end-count_func
}
}
And here is my powershell code, the standard one :
# exit code is non-zero, better retry
Start-Process java "-cp .;.\lib\commons-io-2.4.jar FixedMessageSequenceServer"
Start-Sleep -Seconds 1
Start-Process java "-cp .;.\lib\commons-io-2.4.jar FixedMessageSequenceClient"
When I run the Java code, I need to kill Powershell.exe from the Windows Task Manager, in order to trigger that above waitFor()

JVM on OS X always exiting with status 0 (as captured in Bash script)?

I have a very simple Java class, that does nothing else but:
public class TestMain {
public static void main(String[] args) {
System.out.println("Running!");
System.exit(1111);
}
}
, packed into a TestOSX.jar file.
While on Windows I can run the above snippet and show that %ERRORLEVEL% has the expected value, I get a different outcome on OS X.
Given test.sh containing:
#!/bin/bash
"/Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/bin/java" -jar TestOSX.jar
wait $!
updater_exit_val=$?
echo $updater_evit_val
, I always print 0.
Setup: OS X 10.11.1, Oracle Java 8 u60.
What trivial detail am I missing here?
You do not send your java process to the background with &. Thus wait is executed after the java process exits. It can't find the process you try to wait for, because it already exited and giving return code 0 because of that. $? returns the return code of the last command (in your case wait).
You can either remove wait from your script, or you send your java process to the background by adding & at the end.

Categories

Resources