Running Java applications (.jar
files) automatically during system startup and stopping them gracefully on shutdown can be useful for background services, desktop agents, or local servers. This article explains how to:
- Launch a JAR file silently at system startup
- Stop or kill the JAR when the user logs off or shuts down
- Use VBScript and Windows Task Scheduler for automation
π’ Part 1: Running the JAR on Startup
There are multiple ways to do this, but the most common are:
β
Method 1: Using VBScript
Create a .vbs
file like this:
vbscript
Set WshShell = CreateObject("WScript.Shell")
WshShell.Run "java -jar C:\Path\To\YourApp.jar", 0, False
0
β runs hidden
False
β script continues without waiting
Save it as launchApp.vbs
and place it in:
css
%APPDATA%\Microsoft\Windows\Start Menu\Programs\Startup
This will execute the JAR every time the user logs in.
β
Method 2: Using Task Scheduler (Recommended)
- Open Task Scheduler
- Create a new task
- Set Trigger: "At log on"
- Set Action:
- Program:
java
- Arguments:
-jar "C:\Path\To\YourApp.jar"
- Check "Run whether user is logged in or not"
- Optionally check "Hidden"
This gives more flexibility, especially if you're running services.
π΄ Part 2: Stopping the JAR on Shutdown
Java apps launched in the background (especially via VBScript) may persist beyond normal control. Hereβs how to stop them:
β
Option 1: Java Shutdown Hook (Best for Clean Exit)
Modify your Java code to detect shutdown and handle cleanup:
java
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
System.out.println("App is shutting down...");
// Close resources, save state, etc.
}));
β
Option 2: Use taskkill
in a Shutdown Script
Create a batch file like this:
bat
@echo off
taskkill /F /IM java.exe /T
Save as stopApp.bat
and use Group Policy or Task Scheduler to run this on shutdown:
- Trigger: "On shutdown"
- Action: run
stopApp.bat
Or use a more targeted version:
bat
wmic process where "CommandLine like '%%test.jar%%'" call terminate
This only kills the specific JAR instance.
π‘ Bonus Tips
- Logging: redirect output to a log file with
> log.txt 2>&1
- Silent JAR: use
SystemTray
, TrayIcon
, or keep console hidden - Cross-platform? Look into Java services like Apache Commons Daemon or Java Service Wrapper
β
Summary
TaskMethodRun JAR on startupVBScript in Startup folder or Task SchedulerStop JAR on shutdownShutdown hook in code or Task Scheduler to killBackground & hidden runWshShell.Run
with flags or Task Scheduler