I am running a java program in Windows that collects log from Windows events. A .csv file is created on which certain operations are to be performed.
The commands are execed and piped. How can I cause my Java program to wait until the process is finished?
Here is the code snippet I am using:
Runtime commandPrompt = Runtime.getRuntime();
try {
Process powershell = commandPrompt.exec("powershell -Command \"get-winevent -FilterHashTable @{ logname = 'Microsoft-Windows-PrintService/Operational';StartTime = '"+givenDate+" 12:00:01 AM'; EndTime = '"+beforeDay+" 23:59:59 '; ID = 307 ;} | ConvertTo-csv| Out-file "+ file +"\"");
//I have tried waitFor() here but that does not seem to work, required command is executed but is still blocked
} catch (IOException e) { }
// Remaining code should get executed only after above is completed.
The waitFor() method of Process class is used to wait the currently executing thread until the process executed by the Process object has been completed. The method returns immediately when the subprocess has been terminated and if the subprocess is not terminated, the thread will be blocked.
WaitFor() Causes the current thread to wait, if necessary, until the process represented by this Process object has terminated. WaitFor(Int64, TimeUnit) Causes the current thread to wait, if necessary, until the subprocess represented by this Process object has terminated, or the specified waiting time elapses.
This class is used to create operating system processes. Each ProcessBuilder instance manages a collection of process attributes. The start() method creates a new Process instance with those attributes.
You need to use waitFor()
instead of wait()
. That way your thread will block until the executed command finishes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With