Попытка внедрить CFTHREAD не увенчалась успехом :(

Я ранее сделал сообщение https://stackoverflow.com/questions/17284118/cfhttp-in-cfloop-limit-use-cfthread для создания нескольких запросов CFHTTP, для которых я реализовал решение создания XMLHttpRequest в функции JS для вызова моего запроса CFHTTP из другого файла.

Я изменил это так, чтобы он работал на интервальном таймере, но у меня, похоже, проблема в том, что хост разрешает мне делать только 3 запроса в секунду, но хотя я могу установить интервал времени даже каждые 7 секунд, я по-прежнему истекает время ожидания, потому что запросы CFHTTP, похоже, ожидают обработки и часто делают запрос одновременно (что означает, что я преодолеваю порог).

Я читал сообщения Бена Наделя об использовании CFTHREAD, но совершенно не рад их реализации.

Мой основной процесс на данный момент: -

  • Index.cfm содержит функцию JS, которая использует XMLHttpRequest, вызывающий playerSearch.cfm.
  • playerSearch.cfm делает запрос CFHTTP.
  • Затем playerSearch.cfm зацикливается на ответе, и я отображаю текущий элемент из цикла, а также отправляю другой запрос CFHTTP, чтобы сделать ставку на текущий элемент в цикле, если он соответствует любому из моих условий IF.
  • Затем Index.cfm продолжает делать запросы каждые X секунд.

Есть ли способ настроить сам запрос CFHTTP так, чтобы он выполнял запрос каждые X секунд (возможно, используя функцию сна в CFTHREAD?), и как мне отобразить что-либо внутри CFTHREAD, поскольку я, кажется, не могу?

Кроме того, если бы я мог заставить сам запрос CFHTTP делать запрос каждые X секунд, то было бы мне лучше просто вызывать это напрямую, и будет ли он продолжать непрерывно зацикливаться?

Любая обратная связь будет высоко оценена!

РЕДАКТИРОВАТЬ:

Индекс.cfm

<script>

var searchTimer = null,
    searchInterval = 1000,
    startPosition = 0;

function startSearch() {
    if (searchTimer !== null) return;
    searchTimer = setInterval(function () {
        startPosition = startPosition + 16;
        var xhr = new XMLHttpRequest();
        xhr.open("GET", "playerSearch.cfm?startPosition="+startPosition, true);
        xhr.onload = function (e) {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    document.getElementById("counter").innerHTML = xhr.response;
                } else {
                    // Error handling
                }
            }
        };
        xhr.onerror = function (e) {
            // Error handling
        };
        xhr.send(null);
    }, searchInterval);
}

function stopSearch() {
    clearInterval(searchTimer);
    searchTimer = null
}

</script>

playerSearch.cfm

<cfset Variables.startPosition = URL.startPosition />

<cfhttp url="https://utas.fut.ea.com/ut/game/fifa13/auctionhouse?type=player" method="post" result="getPlayer">
    <cfhttpparam type="header" name="Accept" value="application/json" />
    <cfhttpparam type="header" name="Accept-Language" value="en-GB" />
    <cfhttpparam type="header" name="Connection" value="keep-alive" />
    <cfhttpparam type="header" name="Content-Length" value="1" />
    <cfhttpparam type="header" name="Content-Type" value="application/json" />
    <cfhttpparam type="header" name="COOKIE" value="#Arguments.cookieString#">
    <cfhttpparam type="header" name="Host" value="utas.fut.ea.com" />
    <cfhttpparam type="header" name="Referer" value="http://cdn.easf.www.easports.com/soccer/static/flash/futFifaUltimateTeamPlugin/FifaUltimateTeam.swf" />
    <cfhttpparam type="header" name="User-Agent" value="Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.110 Safari/537.36" />
    <cfhttpparam type="header" name="X-HTTP-Method-Override" value="GET" />
    <cfhttpparam type="header" name="X-UT-Embed-Error" value="true" />
    <cfhttpparam type="header" name="x-flash-version" value="11,7,700,224" />
    <cfhttpparam type="header" name="X-UT-SID" value="#Arguments.sessionID#" />
</cfhttp>

<cfif getPlayer.StatusCode EQ "200 OK">
    <!--- DESERIALIZE RETURNED JSON SO CAN LOOP ROUND EACH RESULT --->
    <cfset Variables.searchResults = DeserializeJSON(getPlayer.FileContent) />

    <!--- IF SEARCH RESULTS RETURNED --->
        <cfset Variables.numResults = ArrayLen(Variables.searchResults.auctionInfo) />
        <cfset Variables.bidsMade = 0 />

        <table width="900" cellpadding="0" cellspacing="0">
            <tr>
                <th width="100" align="left" class="heading">Player Name</th>
                <th width="70" align="left" class="heading">Rating</th>
                <th width="50" align="left" class="heading">Formation</th>
                <th width="80" align="left" class="heading">Position</th>
                <th width="80" align="left" class="heading">Bid Status</th>
                <th width="100" align="left" class="heading">Starting Price</th>
                <th width="80" align="left" class="heading">BIN Price</th>
                <th width="80" align="left" class="heading">Current Bid</th>
                <th width="80" align="left" class="heading">My Bid</th>
                <th width="120" align="left" class="heading">Ends</th>
            </tr>
            <cfloop from="1" to="#Variables.numResults#" index="i"> 

                <cfscript>

                    // DEFAULT BID AMOUNT
                    Variables.bidAmount = 0;

                    // SET BID AMOUNT
                    // IF ITEM HAS BUY NOW PRICE AND IT IS LESS THAN QUICK SELL VALUE THEN BID THAT AMOUNT
                    if (Variables.searchResults.auctionInfo[i].buyNowPrice NEQ 0 AND Variables.searchResults.auctionInfo[i].buyNowPrice LT Variables.searchResults.auctionInfo[i].itemData.discardValue) {
                        Variables.bidAmount = Variables.searchResults.auctionInfo[i].buyNowPrice;
                    }
                    // ELSE IF QUICK SELL VALUE IS 228,231,235,238,242,245 OR 249 BID 200
                    else if (ListFind("228,231,235,238,242,245,249",Variables.searchResults.auctionInfo[i].itemData.discardValue) AND Variables.searchResults.auctionInfo[i].startingBid LTE 200 AND Variables.searchResults.auctionInfo[i].currentBid LT 200) {
                        Variables.bidAmount = 200;
                    }
                    // ELSE IF QUICK SELL VALUE IS 252,256,259 OR 300 BID 250
                    else if (ListFind("252,256,259,300",Variables.searchResults.auctionInfo[i].itemData.discardValue) AND Variables.searchResults.auctionInfo[i].startingBid LTE 250 AND Variables.searchResults.auctionInfo[i].currentBid LT 250) {
                        Variables.bidAmount = 250;
                    }

                    // GET MY CURRENT COIN TOTAL
                    Variables.getCoinTotal = Application.cfcs.Club.getCreditsTotal(SESSION.phishingKey,SESSION.sessionKey);
                    Variables.curCoinsData = DeserializeJSON(Variables.getCoinTotal.FileContent);
                    Variables.curCoins = Variables.curCoinsData.credits;

                    // IF I CURRENTLY HAVE ENOUGH COINS IN ACCOUNT PLACE BID
                    if (StructKeyExists(Variables,"curCoins") AND Variables.bidAmount NEQ 0 AND Variables.bidAmount LT Variables.curCoins) {

                        <cfset Variables.bidData = '{ "bid": ' & Variables.bidAmount & ' }'>
                        <cfset Variables.bidDataLength = Len(Variables.bidData) />

                        <cfhttp url="https://utas.fut.ea.com/ut/game/fifa13/trade/" & Variables.searchResults.auctionInfo[i].tradeID & "/bid" method="POST" result="makeBid">
                            <cfhttpparam type="header" name="Accept" value="application/json" />
                            <cfhttpparam type="header" name="Connection" value="keep-alive" />
                            <cfhttpparam type="header" name="Content-Type" value="application/json" />
                            <cfhttpparam type="header" name="Content-Length" value="#Variables.bidDataLength#" />
                            <cfhttpparam type="header" name="Host" value="utas.fut.ea.com" />
                            <cfhttpparam type="header" name="Referer" value="http://cdn.easf.www.easports.com/soccer/static/flash/futFifaUltimateTeamPlugin/FifaUltimateTeam.swf" />
                            <cfhttpparam type="header" name="X-HTTP-Method-Override" value="PUT" />
                            <cfhttpparam type="header" name="X-UT-SID" value="#SESSION.sessionKey#" />
                            <cfhttpparam type="header" name="COOKIE" value="#SESSION.phishingKey#">     
                            <cfhttpparam type="header" name="User-Agent" value="Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.110 Safari/537.36" />
                            <cfhttpparam type="body" value="#Variables.bidData#" /> 
                        </cfhttp>

                        Variables.bidsMade = Variables.bidsMade + 1;

                    } else {

                        Variables.bidAmount = 0;

                    }
                </cfscript>
                <cfoutput>
                    <tr>
                        <td align="left">#Variables.searchResults.auctionInfo[i].itemData.assetID#</td>
                        <td align="left">
                            #Variables.searchResults.auctionInfo[i].itemData.rating# 
                            <cfif Variables.searchResults.auctionInfo[i].itemData.rareFlag EQ 0>
                                &nbsp;
                            <cfelseif Variables.searchResults.auctionInfo[i].itemData.rareFlag EQ 1>
                                (Rare)
                            <cfelse>
                                (Something else)
                            </cfif>
                        </td>
                        <td align="left">#Variables.searchResults.auctionInfo[i].itemData.formation#</td>
                        <td align="left">#Variables.searchResults.auctionInfo[i].itemData.preferredPosition#</td>
                        <td align="left">#Variables.searchResults.auctionInfo[i].bidState#</td>
                        <td align="left">#Variables.searchResults.auctionInfo[i].startingBid#</td>
                        <td align="left">#Variables.searchResults.auctionInfo[i].buyNowPrice#</td>
                        <td align="left">#Variables.searchResults.auctionInfo[i].currentBid#</td>
                        <td align="left">#Variables.bidAmount#</td>
                        <td align="left">
                            <cfif Variables.searchResults.auctionInfo[i].tradeState EQ "active">
                                <cfset timeLeft = Variables.searchResults.auctionInfo[i].expires />
                                <cfset auctionEnds = DateAdd("s",timeLeft,Now()) />
                                #DateFormat(Variables.auctionEnds,"dd/mm/yyyy")# #TimeFormat(Variables.auctionEnds,"HH:mm:ss")#
                            <cfelse>
                                Ended
                            </cfif>
                        </td>
                    </tr>
                </cfoutput>
            </cfloop>
        </table>
        <br /><br />Bids Made: <cfoutput>#Variables.bidsMade#</cfoutput>
<cfelse><br />
    The search returned an error.
    <cfdump var="#getPlayer#">
</cfif>

person CPB07    schedule 07.07.2013    source источник
comment
Вместо описания кода опубликуйте соответствующие биты. Что-то урезанное, автономное и без чего-либо постороннего поможет нам проанализировать вашу проблему. Я ненавижу рекомендовать это, учитывая все проблемы с безопасностью, с которыми Adobe сталкивается в данный момент, но похоже, что веб-сокеты могут быть чем-то, на что стоит обратить внимание. Хотя из вашего описания не совсем понятно.   -  person Adam Cameron    schedule 07.07.2013
comment
OP обновлен фрагментами кода   -  person CPB07    schedule 08.07.2013
comment
Чтобы ответить на один из ваших вопросов - как бы я мог отображать что-либо внутри CFTHREAD, вы не можете. cfthread работает вне контекста запроса, поэтому некуда возвращать вывод на дисплей. Вам нужно будет написать то, что вам нужно, в файл (или отправить содержимое по электронной почте).   -  person Miguel-F    schedule 08.07.2013