问题
I am running some code as a scheduled task, setup in CF Administrator.
Is there a way to tell in the code that the code ran as a scheduled task, whether it was ran by clicking the run icon in the CF Administrator scheduled task area, or whether it was called directly in a browser?
Adding additional variables will not work?
回答1:
From the test link in the CF admin
If you're asking if you can identify the difference between a scheduled task being run manually by clicking the test link in the coldfusion admin or run on schedule, you can enable logging of scheduled tasks. Any time the task is run by the user the log entry will say [name of job] Executing because of user request at {timestamp}
. If it ran naturally, the log entry will say [name of job] Executing at {timestamp}
I've looked for a way to tell by code and I can't find anything. It would depend on the accuracy of the scheduler but you could look to see if now() is equal to the time of the schedule. Something like (pseudo code):
<!--- disclaimer: I've heard stories that cfschedule sometimes runs a little late --->
<cfset scheduleTime = "2:00 am">
<cfif cgi.HTTP_USER_AGENT eq "CFSCHEDULE" and timeFormat(now(), "h:mm tt") eq scheduleTime>
<!--- ran naturally --->
<cfelse>
<!--- ran by force --->
</cfif>
From a browser
If you want to know if your scheduled task was run by the schedule or if the file was hit by the browser you can look at cgi.HTTP_USER_AGENT
. if it is run by the scheduler it will equal CFSCHEDULE
otherwise it will equal whatever the client is set to send.
Perhaps, Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11
or if you're lucky enough to have a bot hit it, something like: Mozilla/5.0 (compatible; MJ12bot/v1.4.3; http://www.majestic12.co.uk/bot.php?+)
It is possible to spoof the client or server request to make the user user agent to say CFSCHEDULE but it isn't likely.
on a side note...
The default user agent for cfhttp is "COLDFUSION", in case you were interested.
来源:https://stackoverflow.com/questions/13977831/how-do-i-determine-if-a-scheduled-task-was-ran-automatically-or-ran-in-a-browser