Using Ant to start and stop tomcat service

This short guide will describe how to start and stop Tomcat using Ant.

This was tested using Ant 1.9.6 and Tomcat 8.0.30 on a Windows 10 machine.

Requirements

Ant should be installed and the /bin folder should be added to the windows path. Tomcat should be installed and be running as a service in windows.

Ant build.xml

First we need to define a macro in Ant for calling a service

<property name="servicename" value="Tomcat8" />

<macrodef name="service">
    <attribute name="service" />
    <attribute name="action" />
    <sequential>
        <exec executable="cmd. exe">
            <arg line="/c net @{action} '@{service}'" />
        </exec>
    </sequential>
</macrodef>

Note: The call to the command prompt should of course be without a space before “exe” – but my host has mod_security installed which prevents me from saving if i remove the space. Haven’t figured out how to get around this yet…. The same problem occurs in the code below.

First the property servicename is defined setting the value to the name of the Tomcat service.
The “action” attribute can be either start or stop and the “service” attribute is the name of the service. The macro just calls “net start” or “net stop” from a command prompt.

The next thing we need to do, is to write a target for starting Tomcat and one for stopping Tomcat – and lets add restart for good measure.

<target name="startTomcat">           
    <service action="start" service="${servicename}" />		
    <sleep seconds="10"/>
</target>
	
<target name="stopTomcat">
    <service action="stop" service="${servicename}" />
    <sleep seconds="10" />
    <exec dir="." executable="cmd. exe">
    	<arg line ="/c taskkill /f /fi 'services eq ${servicename}' " />
    </exec>
    <sleep seconds="10" />
</target>

<target name="restartTomcat" depends="stopTomcat, startTomcat" />

The startTomcat target is straight-forward. I added a sleep of 10 seconds just to ensure that Tomcat has the needed time to start. Depending on your usage, this might be removed or increased to suit your needs – it is also possible to write minutes=”2″ for it to wait two minutes.

The stopTomcat target is a bit more complex. First I stop the service, then wait 10 seconds to give it enough time to shut down – then i kill the process in case it has not been shut down yet.

Hope this is useful to someone, took me a bit of fiddling to get working :)