coldfusioncfc

Forcibly stop the execution of the function in the cfc component


Does anyone know how I can forcibly stop a function execution in the cfc component if it works for more than a certain time? Either it may be piece of code, not a whole function, i.e. if it has completed in 5 seconds, I take some actions, otherwise others.


Solution

  • The only way to stop an arbitrary piece of code is to run it in a separate thread and then terminating after a set amount of time. This can be done by calling out to a separate page with a request timeout set or using cfthread.

    For example with thread... (Note.... as Alex pointed out you can use timeout on cfthread)

    <cfthread action="run" name="runForLimitedTime">
        ... code, call to function, etc ...
    </cfthread>
    
    <cfset sleep(5000) />
    
    <cfif cfthread.runForLimitedTime.status eq "COMPLETED">
        <cfthread action="join" />
    <cfelse>
        <cfthread action="terminate" name="runForLimitedTime" />
    </cfif>
    

    Alternatively with a separate page...

    <!--- calling page --->
    
    <cfset error = false />
    <cftry>
        <cfhttp url="pageSetupForSpecificCall.cfm?timeout=5" throwonerror="true" />
        <cfcatch>
            <cfset error = true />
        </cfcatch>
    </cftry>
    
    <cfif error>
        something
    <cfelse>
        something else
    </cfif>
    
    
    <!--- pageSetupForSpecificCall.cfm --->
    
    <cfsetting requesttimeout="#url.timeout#" />
    
    ...do things...