Schedule a executable file without Windows task scheduler - java

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.

Related

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.

Java ShutDownHook not being fired on Windows

Ive got the following ShutdownHook to detect when the application is exited:
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
public void run() {
// Do what you want when the application is stopping
sendMsg("", "goOfflineExit", "12");
}
}));
This works perfectly on Mac os but for some reason nothing gets fired on Windows.
Any ideas what im missing?
I can think of two possible explanations:
The sendMsg(...) call may be happening too late; e.g. after streams have been closed or flushed.
The sendMsg(...) call may be throwing an exception. Uncaught exceptions thrown in a shutdown hook typically don't get reported.
If you showed us the code of sendMsg we might be able to figure out a more definite answer.

Java Shutdown function not executing

Within the main() of my application I have the following code to back up data so it doesn't get lost in the event of a system shut down.
//add hook to trigger Production Shutdown sequence
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
public void run() {
Production.shutdown();
}
}));
However, whether I press the Stop button in my IDE or rely on input via the log (code shown below) it never seems to save data to the database or write any logs to the console.
ctx.deploy(server);
server.start();
//start the production process
Production.init();
System.in.read();
server.stop();
How come this shutdown function is not being executed?
You need to use the Exit button, not Stop, see my answer here for more details.
Note that this feature is currently available only in Run mode, not in Debug.
System.exit(0)
add this line in your code. Debug from here onwards

Shutdown hook from UNIX

I am trying to get my Java program to exit gracefully on my unix server. I have a jar file, which I start through a cron job in the morning. Then in the evening, when I want to shut it down, I have a cron job which calls a script that finds the PID and calls kill -9 <PID>. However, it doesn't seem that my shutdown hook is activated when I terminate this way. I also tried kill <PID> (no -9) and I get the same problem. How can I make sure the shutdown hook gets called? Alternatively, perhaps there is a better way to kill my process daily.
class ShutdownHook {
ShutdownHook() {}
public void attachShutDownHook() {
Runtime.getRuntime().addShutdownHook(new Thread() {
#Override
public void run() {
System.out.println("Shut down hook activating");
}
});
System.out.println("Shut Down Hook Attached.");
}
}
You can use code like this on Unix to trap SIGINT (#2) signal:
Signal.handle(new Signal("INT"), new SignalHandler() {
public void handle(Signal sig) {
// Forced exit
System.exit(1);
}
});
kill -9 <pid> sends a KILL signal. This signal cannot be intercepted by the program.
If you call kill <pid>, the TERM signal (15) wil be sent. In that case, the JVM will catch the signal and the shutdown hooks will be executed.
This has nothing to do with the signals the JVM is trapping/receiving but everything to do with the terrible shutdown process of Gnome, which apparently needs to be cooperative not to absolutely shit the bed (and the jdk doesn't have the api for this). If you want to see a even worse consequence of this, try to run:
dbus-monitor --profile --session type='method_call',interface='org.gnome.SessionManager'
on a shell, and logout or restart: it will crash gnome-shell and hang the computer until you login on a TTY and order a restart.
Maybe kdbus will fix this on this case, maybe not. The only thing i know is that shutdownhooks on a java application that is using AWT (not command line) will NEVER run its shutdownhooks on GNOME3. Actually, the VM will always exit with non-zero code (failure) presumably from native code. At least it doesn't hang, although this makes shutdown hooks quite useless
(i've been trying to make a workaround by using dbus-monitor, but as you can see from the example i gave, it's a bit too dangerous too).

Executing batch from 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.

Categories

Resources