We help IT Professionals succeed at work.

How to determine if there is another .CFM already running

Errol Farro
Errol Farro used Ask the Experts™
on
I have two .CFM, a1.cfm and a2.cfm, that cannot run at the same time. While a1.cfm is running and someone wants to start a2.cfm, a2.cfm should get the message that a1.cfm is already active and that a2.cfm cannot start.

Conversely, while a2.cfm is running, a1.cfm cannot be invoked.

Is there a ColdFusion command which can very if there is a .CFM already running ?
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2015
Commented:
AFAIK there isn't anything built in that will tell you if a template is running.  One possibility is to store a boolean variable in the application scope, which indicates whether one of the scripts is currently executing.  Check the flag at the start of each script. If it's true, display the error message and abort. Otherwise, set the variable to true and execute the script. Resetting it to false when finished. A few things to watch out for.

- To avoid race conditions, be sure to use a lock when updating the variable
- Also, be sure to always reset the application variable at the end of the script, even if an error occurs

You could also use this trick .  Wrapping the code of both templates in an exclusive named lock will prevent them from being executed at the same time.  Just be sure they both use the same lock name.  Here's an example

A1.cfm
<h1>A1.cfm</h1>

<cfset allowExecute = false>

<!--- both templates must use the same lock name --->
<cflock name="Some_Shared_Name_Here" type="exclusive" timeout="1" throwontimeout="false">

	<!--- set flag to indicate template executed --->
	<cfset allowExecute = true>

	<!--- simulate long running cfml code --->
	<cfset sleep(10000)>
</cflock>	

<cfif !allowExecute>
	Template A2.cfm is already active. This script cannot be invoked at this time.
<cfelse>
	<br>Finished executing template<br>
</cfif>

Open in new window


A2.cfm

<h1>A2.cfm</h1>

<!--- both templates must use the same lock name --->
<cflock name="Some_Shared_Name_Here" type="exclusive" timeout="1" throwontimeout="false">

	<!--- set flag to indicate template executed --->
	<cfset allowExecute = true>

	<!--- simulate long running cfml code --->
	<cfset sleep(10000)>

</cflock>	

<cfif !allowExecute>
	Template A2.cfm is already active. This script cannot be invoked at this time.
<cfelse>
	<br>Finished executing template<br>
</cfif>

Open in new window

Charlie ArehartTroubleshooting Consultant

Commented:
FWIW, I'll concur that there is no programmatic way built into cf to determine what's already running, and that either of the two alternatives offered by agx that are just what I would also have offered. I can't think of any better solution.