Task Scheduler: Run a Java program after a Python script finishes - windows

I need to do two things every 10 mins or so:
1) Run a python script
2) Once the above script finishes to completion, run the Java program (JAR file)
I'm using Windows Task scheduler for this. I've come across these two links:
https://technet.microsoft.com/en-us/library/cc772785%28v=ws.10%29.aspx
https://technet.microsoft.com/en-us/library/cc755618%28v=ws.10%29.aspx
but I'm just not sure how to go ahead with this. Can I write some powershell script or something which can take care of this? Any help is extremely appreciated. Thanks.

You could do that with a powershell script. You can execute a programm and then wait until it has finished its taks like this:
While($True)
{
Start-Process $PythonPath -Wait
Start-Process $JavaPath -Wait
Start-Sleep -m 10
}

in a background task you can define several actions that would be processed one after the other. So I would just create a background task in the Windows Task Scheduler, set the trigger and create two actions, first your python script and then the execution of your java program. Unless the python script returns before it is completed, your two actions will be processed in sequence.

Related

How to prevent Powershell from killing its own background processes when spawned via SSH?

We have a Powershell script in C:\test\test.ps1. The script has the following content (nothing removed):
Start-Process -NoNewWindow powershell { sleep 30; }
sleep 10
When we open a command line window (cmd.exe) and execute that script by the following command
c:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -File C:\test\test.ps1
we can see in the Windows task manager (as well as Sysinternals Process Explorer) that the script behaves as expected:
Immediately after having executed the command above, two new entries appear in the process list, one being Powershell executing the "main" script (test.ps1), and one being Powershell executing the "background script" ({ sleep 30; }).
When 10 seconds have passed, the first entry (related to test.ps1) disappears from the process list, while the second entry remains in the process list.
When additional 20 seconds have passed (that is, 30 seconds in sum), the second entry (related to { sleep 30; }) also disappears from the process list.
This is the expected behavior, because Start-Process starts new processes in the background no matter what, unless -Wait is given. So far, so good.
But now we have a hairy problem which already has cost us two days of debugging until we finally figured out the reason for the misbehavior of one of our scripts:
Actually, test.ps1 is executed via SSH.
That is, we have installed Microsoft's implementation of the OpenSSH server on a Windows Server 2019 and have configured it correctly. Using SSH clients on other machines (Linux and Windows), we can log into the Windows Server, and we can execute test.ps1 on the server via SSH by executing the following command on the clients:
ssh -i <appropriate_key> administrator#ip.of.windows.server c:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -File C:\test\test.ps1
When observing the task manager on the Windows Server, we can again see the two new entries in the process list as described above as soon as this command is executed on a client.
However, both entries then disappear from the process list on the server after 10 seconds.
This means that the background process ({ sleep 30; }) gets killed as soon as the main process ends. This is the opposite of what is documented and of what should happen, and we really need to prevent it.
So the question is:
How can we change test.ps1 so that the background process ({ sleep 30; }) does not get killed under any circumstances when the script ends, even when the script is started via SSH?
Some side notes:
This is not an academic example. Actually, we have a fairly complex script system in place on that server which consists of about a dozen of Powershell scripts, one of them being the "main" script which executes the other scripts in the background as shown above; the background scripts themselves in turn might start further background scripts.
It is important to not start the main script in the background via SSH in the first place. The clients must process the output and the exit code of the main script, and must wait until the main script has done some work and returns.
That means that we must use Powershell's capabilities to kick off the background processes in the main script (or to kick off a third-party program which is able to launch background processes which don't get killed when the main script ends).
Note: The original advice to use jobs here was incorrect, as when the job is stopped along with the parent session, any child processes still get killed. As it was incorrect advice for this scenario, I've removed that content from this answer.
Unfortunately, when the PowerShell session ends, so too are child processes created from that session. However, when using PSRemoting we can tell Invoke-Command to run the command in a disconnected session with the -InDisconnectedSession parameter (aliased to -Disconnected):
$icArgs = #{
ComputerName = 'RemoteComputerName'
Credential = ( Get-Credential )
Disconnected = $true
}
Invoke-Command #icArcs { ping -t 127.0.0.1 }
From my testing with an infinite ping, if the parent PowerShell session closes, the remote session should continue executing. In my case, the ping command continued running until I stopped the process myself on the remote server.
The downside here is that it doesn't seem you are using PowerShell Remoting, but instead are invoking shell commands over SSH that happen to be a PowerShell script. You will also have to use PowerShell Core if you require the SSH transport for PowerShell remoting.

Unable to run a windows task that makes https request under SYSTEM account

I have created a windows cmd file that calls three independent bat files. I want to create a windows task that calls this cmd file and runs every 5 minutes. The problem is that this task runs perfectly fine only when I'm logged into the system. But I'm unable to make this task continue to run "whether I'm logged in or not".
I even asked my colleague to login to that machine and run this task under his account - it worked. I created a local admin user on that machine, logged in as that user, tried to run this task - it did not work - the script waits forever while post_results.bat. I even tried to schedule a jenkins job that basically does the same thing - it did not work - the jenkins job waits forever while post_results.bat (I killed the jenkins job after waiting for ~20 min).
Here is a summary of what these tasks are doing:
run_all.cmd
call "run_test.bat"
call "post_results.bat"
call "clean.bat"
run_test.bat - executes a jmeter script
C:\Users\Administrator\LS2\apache-jmeter-4.0\bin\jmeter -n -t api_strategy_synthetic_tests.jmx -JTestEnv=amer1 -l Result_log.jtl
post_results.bat - calls a python script that posts the jmeter test results to datadog
python post_jmeter_results_to_datadog.py Result_log.jtl
post_jmeter_results_to_datadog.py - uses the datadog python api to post metrics to datadog
#!/usr/bin/env python3
import sys
import pandas as pd
from datadog import initialize, api
options = {
'api_key': <API_KEY>,
'app_key': <APPLICATION_KEY>
}
initialize(**options)
jtl_file = sys.argv[1]
df = pd.read_csv(jtl_file)
for index, row in df.iterrows():
tag = "success:" + str(row['success'])
api.Metric.send(
metric=row['label'],
points=[(row['timeStamp']/1000,row['elapsed'])],
tags=[tag]
)
clean.bat - deletes the jmeter test result files
rmdir /s /q "errors"
del "jmeter.log"
del "Result_log.jtl"
All I need is to be able to run this task every 5 minutes. If anyone is able to see what I'm doing wrong and points that out... I'd be really grateful.
You can create one PowerShell script to execute your Batch scripts remotely.
And Even you can schedule your PowerShell script using Windows Task Scheduler which will run as per your settings.

running shell script with windows task scheduler

I currenty have a simple shell script that I created for a linux machine to be run using cron, but now I want to be able to run the file using windows task scheduler. I have tried to get it to work using cron for cygwin, but even after running cron-config successfully and ensuring that the shell script can be executed successfully, for some reason the cron task simply wasn't executing. So I decided to give in and use the windows task scheduler. In order to do this, I looked at the following posts about the issue:
Cgywin .sh file run as Windows Task Scheduler
http://www.davidjnice.com/cygwin_scheduled_tasks.html
in my case, the entry in the "actions" tab of the new task looks like this:
program/script: c:\cygwin64\bin\bash.exe
arguments: -l -c "/cygdrive/c/users/paul/bitcoinbot/download_all_data.sh >> cygdrive/c/users/paul/bitcoinbot/logfile.log 2>&1"
start in: c:\cygwin64\bin
Notice that I redirected the output of the shell script to a log file, so that I should be able to see there whether the program run. Other than that, I simply edited the "trigger" tab to run the task daily, and set the time to a couple of minutes in the fture to see whether it ran successfully.
Alas, when I look at the detailed event history for the task, nothing changes when the trigger time passes. And when I manually "run" the task, the event history seems to add a few different events, but the task is completed within seconds, whereas this task should take over an hour (and it does when the shell script is executed directly from the terminal). And when I look for the log file that should have been created, there is nothing.
Does anyone have any idea what might be the issue here? How can I get my task to run properly at the trigger time, and how can I make sure it does so?
Best,
Paul
EDIT:
here are the pictures showing event history, as per Ken White's request.
Please ignore the fact that it says there are 24 events. These are from multiple separate runs of the task. The events shown here are a complete list of the events triggered by a single run.
EDIT 2:
Regarding my attempts to get cron to work, I have run into the following problem when I try to start the cron service using cygrunsrv. First of all, I tried to start cron by typing
cygrunsrv -I cron -p /usr/sbin/cron.exe -a -D
Now when I type
$cygrunsrv -Q cron
Service: cron
Current State: stopped
Command: /usr/bin/cron.exe
Now, I tried to start the cron service by typing
cygrunsrv -S cron
Cygrunsrv: Error starting a service: QueryServiceStatus: Win32 error 1062:
The service has not been started.
Does anyone hae any idea what this error means? I tried googling it, but couldn't find any answers.

Calling cscript.exe and passing a vbscript to call

I have scheduled a task in windows server 2008R2 ..I want to run a VBScript so when I setup the task I call the cscript at C:\Windows\System32\cscript.exe and in the arguments section I am passing //nologo //B d:\main\programs\copy.vbs /targets:contents but it is not executing my script ..If I call my script directly in the start program section it works fine but it's not working if I call CSrcipt and pass in arguments the status changes to queued but nothing happens after that..Can someone tell me what I am doing wrong here.
Also another question I have is that can we run 2 programs one after another in one task like when one script is finished I would like to start another script .
Thanks
Put this line at the top of your script and try again:
CreateObject("WScript.Shell").LogEvent 4, "Script running"
Unless you get an Information event with source WSH and event-ID 4, your script isn't running at all. Check the eventlog and the task's History tab for clues as to why that is. Also check the permissions of the script. Is the runas account of the task able to access/run the file? You can check that by starting a CMD instance as that user
runas /user:DOM\USER cmd
and then trying to run the script in that CMD instance.
Also double-check the task settings. As which user is it configured to run? With the user logged on or not logged on? Is "Run with highest privileges" enabled (in case UAC is enabled on your server)?
If the script does produce the abovementioned event that means it's running in principle, but something is going wrong in the process. You need to debug your script.

Windows 2008 Task Scheduler Return Code and Matlab Script

How do I allow my Matlab script to pass back a return code to the Task Scheduler? I currently have a task that runs "matlab -r myscript". The problem is the Task Scheduler always succeeds immediately after starting, even though myscript takes several minutes to run. So, I don't see how to pass back an error code.
How can I make Task Scheduler wait until the script stops running and then get matlab to pass back a return code?
Use the matlab -wait command line option to have it block until the program is finished.
There appears to be an undocumented argument to quit() to set the exit status - e.g. quit(42) - which then shows up in %ERRORLEVEL%. Since it's undocumented, you might not want to rely on it. Alternatively, have your script write its status to a file and have a wrapper script parse it.

Resources