Executing batch from Java - java

Let's say,
I have a Java class JavaClass1.java.I am executing 2 batch files from this Java class.
Each .bat files starts another Java application.
Lets say these other two app takes 15 hour each to complete, and they are also not dependent to each other.
How can I solve this issue. I dont have to wait for one to complete so that I have to
start another, I can do it simultaneously also.
I found people talking about handelling outputstream, inputstream and error stream, if I
wait for the errors to handle, then I have to wait 15 hours for each. I dont want to do that.
Is there any way? Please suggest. Thanks

Place the mechanism for launching each .bat in its own thread, then start each thread.
new Thread(new Runnable() {
#Override
public void run() {
//Launch first bat.
}
}).start();
new Thread(new Runnable() {
#Override
public void run() {
//Launch second bat.
}
}).start();

Runtime.getRuntime().exec(new String[]{"cmd","/c","java -jar app1.jar"});
Runtime.getRuntime().exec(new String[]{"cmd","/c","java -jar app2.jar"});
Just use Runtime execute service, if you don't call process.waitFor() to get return code of process, it won't blocking, so you can call next app immediately. If you want return code from app, run app on each Thread as Mike.

Related

Proper use of threads in using Java and Servlets

I am pretty new in the whole Servlets area and I am trying to implement a method that will wait for an a time variable given by a user( e.g 1 minute) and then it will start a countdown until the given time reaches 0. I thought the only way I can do that is by using Threads.
I am exporting my Java Project as a war , deploy it but when I import 1 minute the webpage does not prints anything until I reload it and If I go back using my browser the thread is still running.
The code below executes the thread.
Can you please suggest me whether I should use the asychronous threads (and maybe explain a little bit the difference with normal threads) or I can continue using the Thread as it is.
if(minutes<=0) {
out.println("<center><h3>Time cannot be negative</h3></center>");
}
else
{
new Thread(new Runnable(){
public void run() {
try {
out.println("<center><h3>Minutes :"+(minutes)+"</h3></center>");
Thread.sleep(minutes*60000);
out.println("<p align=\"CENTER\"> Return<br>");
} catch (InterruptedException e) {
out.println("Interruption Found");
}
}
}).start();
}
}
You have to answer the HTTP request, without delay. A thread isn't a solution for that.
You may use one of the following:
Using some Ajax (client side controlled)
WebSocket (server side controlled)

How to Run Java program in Background at every specific interval of time? [duplicate]

This question already has answers here:
need to run specific functionality at specific interval in java
(2 answers)
Closed 6 years ago.
I had written a simple java code on Raspberry Pi which is sending data from raspberry Pi to server. Now instead of running a program manually I want that program is executed in every 10(any specific time) second automatically in background, so new data is sending to the server after that amount of time. Raspberry Pi is running on Raspbian OS.
Can someone help me out as to how this can be done? Thank you in Advance..
You have two options: run your job periodically from cron or something similar or change your application to long running process that will run as a service on your device and will perform its own scheduling. Libraries like Quartz (http://www.quartz-scheduler.org/) can be used to do the latter. Slight advantage of a long running job can be smaller penalty when launching the job (initialization and tear-down of JVM).
You can use a java.util.Timer for your application instead Thread.
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
//write your code here
System.out.print(new Date() + "\n");
}
}, 0, 1000);
I think it's the easiest way to solve your problem.
You could use a Thread to execute your code at specific time points.
Example:
Thread thread = new Thread(new Runnable(){
#Override
public void run() {
while(true){
try{
//your code
Thread.sleep(10*1000);//this is poll interval
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
});
thread.setDaemon(true);
thread.start();
I found answer for this.
Using crontab you can execute task at specific interval of time.
For java file you have to make a jar file and then if you want to run after every one minute then the syntax for crontab is
java -jar /path_of_your_jar_file/File_name.jar
But here the problem is your task is repeated every 1 minute. So If you want to make it in 10second then you have to use thread sleep for that.
Code for Thread sleep is
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
method_name();
}
},0,10000);

Java shutdown hook not running

I have a product service in Java. In our code I am creating shut down hook, but when I stop service it is not calling shut down hook consistently. Out of 5 stop calls it has called shutdown hook only once.
Runnable shutdownHandler = new Runnable() {
#Override
public void run() {
s_log.info("Shutting down thread..");
}
};
Runtime.getRuntime().addShutdownHook(
new Thread(shutdownHandler, "shutdownthread"));
Can anybody please tell me what could be the reason behind this not getting called consistently?
Check the following code:
Runnable shutdownHandler = new Runnable() {
#Override
public void run() {
System.out.println("Shutting down thread..");
}
};
Runtime.getRuntime().addShutdownHook(
new Thread(shutdownHandler, "shutdownthread"));
and if it gives you expected output, you need to check the documentation of your logging framework.
I am also finding that my framework (Jooby) and Java shutdown hooks work fine on my Mac on IntelliJ which sends a kill SIGINT (-2) however on Ubuntu Server 20.04 LTS they don't run.
As my Java app is a webapp I came up with a simple workaround:
Setup a controller to listen to some url that isn't easily guessable e.g.
/exit/fuuzfhuaBFDUWYEGLI823y82941u9y47t3u45
Have the controller simply do the following:
System.exit(0)
Do a curl or wget from a script to the URL and the shutdown hooks all fire as JVM comes down.
I suspect for some reason on Linux there is a bug and no matter what interrupt that I use besides SIGKILL they all effectively behave like SIGKILL and the JVM comes down hard/abruptly.

Schedule a executable file without Windows task scheduler

Is it possible to schedule a executable file to run just before log-off using java?
I am working on a application that needed to send a message to the sever just before the system log-off/shutdown. But I didn't find any method to solve it. If anyone know plz help me.
Thanks in advnce.
As stated in the comments a ShutdownHook is probably what you are searching for.
Short example:
Runtime.getRuntime().addShutdownHook(new Thread() {
#Override
public void run() {
// Code to be executed when JVM exits
System.out.println("JVM exit");
}
});
Note that the ShutdownHook will execute whenever the JVM exits. So it will also execute when your program terminates normally.
If you have any further questions comment on this answer.

Java input without pausing

How would I make a sort of console for my program without pausing my code? I have a loop, for example, that needs to stay running, but when I enter a command in the console, I want the game to check what that command was and process it in the loop. The loop shouldn't wait for a command but just have an if statement to check if there's a command in the queue.
I'm making a dedicated server, by the way, if that helps.
Have them run in two separate threads.
class Server {
public static void main(String[] args) {
InputThread background = new InputThread(this).start();
// Run your server here
}
}
class InputThread {
private final Server server;
public InputThread(Server server) {
this.server = server;
}
public void run() {
Scanner sc = new Scanner(System.in);
while(sc.hasNextLine()) {
// blocks for input, but won't block the server's thread
}
}
}
There's pretty obvious approach: use a dedicated thread to wait on InputStream, read events/commands from it and pass them into a queue.
And your main thread will be regularly checking this queue. After every check it will either process a command from the queue or continue what it was doing if it's empty.
What you'd like to have is a thread in which you keep the command reading code running. It'd probably look something like this:
class ReadCommand implements Runnable
{
public void run()
{
// Command reading logic goes here
}
}
In your "main" thread where the rest of the code is running, you'll have to start it like this:
new Thread(new ReadCommand())).start()
Additionally, you need a queue of commands somewhere which is filled from ReadCommand and read from the other code.
I recommend you to read a manual on concurrent java programming.
The server should run in its own thread. This will allow the loop to run without pausing. You can use a queue to pass commands into the server. Each time through the loop the server can check the queue and process one or more commands. The command line can then submit commands into the queue according to its own schedule.
You can read from the console in a separate thread. This means your main thread doesn't have to wait for the console.
Even server applications can have a Swing GUI. ;)

Categories

Resources