Skip to main content
Ben Nadel at cf.Objective() 2012 (Minneapolis, MN) with: Vicky Ryder
Ben Nadel at cf.Objective() 2012 (Minneapolis, MN) with: Vicky Ryder

Expired SESSION Available In ColdFusion CFThread Tag

By
Published in Comments (8)

Not too much to see here; I just took my previous session expiration post and applied it to ColdFusion's asynchronous threading. Basically, I wanted to make sure that a SESSION which has ended mid-page request would still be available in subsequent threads launched by the current page request (after the session has expired). But, before I even show the code, I just want to point out that it is probably not good practice to refer to the SESSION scope within the CFThread body unless explicitly passed via the CFThread tag attributes (think proper encapsulation and low coupling).

First, I had to update my Application.cfc. Since CFThreads cannot output data to the screen, I added a logging function that would write a value and time stamp to a local log file. Then, I also included the OnRequest() event method so that the log function would be available in the THIS scope (the whole page request becomes an Application.cfc mixin).

<cfcomponent
	output="false"
	hint="Handle the application configuration.">


	<!---
		Set the application settings. Notice that we
		are creating sessions that only last for 2 seconds.
	--->
	<cfset THIS.Name = "TimeoutTest" />
	<cfset THIS.ApplicationTimeout = CreateTimeSpan( 0, 0, 1, 0 ) />
	<cfset THIS.SessionManagement = true />
	<cfset THIS.SessionTimeout = CreateTimeSpan( 0, 0, 0, 2 ) />


	<!--- Set the page request settings --->
	<cfsetting
		showdebugoutput="false"
		/>


	<cffunction
		name="OnSessionStart"
		access="public"
		returntype="boolean"
		output="false"
		hint="Fires when the user's session begins.">

		<!--- Store the date created. --->
		<cfset SESSION.DateCreated = Now() />

		<!--- Return out. --->
		<cfreturn true />
	</cffunction>


	<cffunction
		name="OnRequest"
		access="public"
		returntype="void"
		output="true"
		hint="Executes the requested template.">

		<!--- Define arguments. --->
		<cfargument
			name="Template"
			type="string"
			required="true"
			hint="The ColdFusion template that has been requested."
			/>

		<!--- Include the template. --->
		<cfinclude template="#ARGUMENTS.Template#" />

		<!--- Return out. --->
		<cfreturn />
	</cffunction>


	<cffunction
		name="OnSessionEnd"
		access="public"
		returntype="void"
		output="false"
		hint="Fires when the session is terminated.">

		<!--- Define arguments. --->
		<cfargument
			name="Session"
			type="struct"
			required="true"
			hint="The expired session scope."
			/>

		<!--- Store the date destroyed. --->
		<cfset ARGUMENTS.Session.DateEnded = Now() />

		<!--- Return out. --->
		<cfreturn />
	</cffunction>


	<cffunction
		name="LogValue"
		access="public"
		returntype="void"
		output="false"
		hint="Logs the given value to a local log.">

		<!--- Define arguments. --->
		<cfargument
			name="Value"
			type="string"
			required="true"
			hint="The value to be logged."
			/>

		<!--- Set up the output. --->
		<cfset var Output = (
			ARGUMENTS.Value & " : " &
			TimeFormat( Now(), "hh:mm:ss" )
			) />

		<!--- Log value / time stamp to txt file. --->
		<cffile
			action="append"
			file="#ExpandPath( './log.txt' )#"
			output="#Output#"
			addnewline="true"
			/>

		<!--- Return out. --->
		<cfreturn />
	</cffunction>

</cfcomponent>

Then, I created a simple Index.cfm page that sleeps for 10 seconds (so as to ensure session expiration) and then launches an asynchronous thread:

<!---
	Sleep the primary page request thread to make sure
	that the SESSION has expired by the time we launch our
	asynchronous thread.
--->
<cfthread
	action="sleep"
	duration="#(10 * 1000)#"
	/>


<!---
	Launch asynchronous thread. At this point, the user's
	SESSION will have already ended.
--->
<cfthread
	action="run"
	name="thread1">

	<!---
		Check to see if the session has timed out (this should
		always be the case, but just a precaution).
	--->
	<cfif StructKeyExists( SESSION, "DateEnded" )>

		<!--- Log session timeout time. --->
		<cfset THIS.LogValue(
			"Session Ended " &
			"(#TimeFormat( SESSION.DateEnded, 'hh:mm:ss' )#)"
			) />

	</cfif>

</cfthread>

There's a couple of things to notice here. For starters, I am sleeping the primary thread (originally requested page) for 10 seconds. This will cause the user's session to expire before our CFThread tag is executed (confirmed via the logging output). Additionally, I am referring to the THIS scope within the CFThread tag body. Because we are using the OnRequest() event method, the entire page essentially becomes part of the Application.cfc and therefore has access to all of its scopes.

Running this page, we get the following log data:

Session Ended (08:48:30) : 08:48:35

As you can see, the SESSION expired at 30 seconds and the thread fired at 35 seconds, 5 seconds after the OnSessionEnd() method was called. Sweet. This just means that as with the primary page request, we never have to worry about session expiration within an asynchronous thread.

Want to use code from this post? Check out the license.

Reader Comments

357 Comments

"I added a logging function that would write a value and time stamp to a local log file"

Err... why not cflog? The only reason I can see to do this would be for cases when you don't have access to normal CF logs.

15,848 Comments

@Ray,

To be honest, I find it a real pain to go to the CFLogs. Our logs are like a million miles long and take forever to load (I don't manage that stuff and I don't know much about them). As such, I find it easier to make something quick and small for a local file.

15,848 Comments

@Ray,

Where is that log file located? If I can give it a custom path, then I am all for it. But, if I still need to actually go to the ColdFusion Admin to view it, still feels a little overkill... no, overkill is not the right word. I guess I mean that it requires to much "system context".

15,848 Comments

@Ray,

Ha ha, I was about to say something like, Wouldn't it be cool if they made a CFLog tag where you could define the output and path the file.... then I was like, oh wait, that's what CFFile does :)

I guess the convenient thing about CFLog is that you don't have to worry about file paths.

92 Comments

If you need to see a data dump logged I suggest using the format and output attributes of cfdump! Logs are great but usually whenever I debug something I prefer cfdumps since I can see any sort of complex data. I know this isn't really about debugging but since cflog was mentioned I just thought I'd bring up some of the new features cfdump has gotten in CF8.

15,848 Comments

@Javier,

You raise a great point. I am a huge fan of CFDump, but have not really leveraged it yet in ColdFusion 8. Since so much of my CF8 stuff is theoretical (not on production yet), these types of things are not second nature yet. CFDump in CF8 has some great stuff including writing directly to a text file.

I believe in love. I believe in compassion. I believe in human rights. I believe that we can afford to give more of these gifts to the world around us because it costs us nothing to be decent and kind and understanding. And, I want you to know that when you land on this site, you are accepted for who you are, no matter how you identify, what truths you live, or whatever kind of goofy shit makes you feel alive! Rock on with your bad self!
Ben Nadel