簡體   English   中英

在Spring Web應用程序中使用計時器跟蹤用戶操作

[英]Using a timer for tracking user action in a Spring web application

我正在Spring Hibernate中開發一個管理應用程序,其中我需要實現一個計時器系統。

使用案例

  1. 用戶單擊UI(jsp)上的活動或事件。 計時器啟動,它在UI上顯示倒計時。 只有在規定的計時器計數結束后,用戶才能再次執行該事件。

  2. 我需要將時間保留在數據庫中,因為如果用戶關閉瀏覽器,計時器計數應在服務器中繼續。 就像我們在基於網絡的社交媒體游戲中遇到的方式一樣。

我在網上搜索了一個解決方案,但沒有發現任何問題。 我嘗試了Spring Scheduling,但似乎無法解決問題,而且有很多局限性。

誰能建議我任何解決方案? 謝謝

為了回答這個問題,我將假設以下內容:

  1. 在后端,您可以運行異步后台作業
  2. 前端的JavaScript計時器足以進行倒計時(無論后台作業有多慢

基本思想是,您向服務器發送日期戳,在前端開始倒計時,並且只要有互動可以再次嘗試該活動,就詢問服務器(相同的后台任務)時間是否間隔已完成。

下面的解決方案只是一個開始,絕不是管理這種交互所需要的完整版本。

在前端,您可以想象執行以下操作:

function restoreAndStartTimer(response, initialLoad){
   var secondsToCountDown = 10;
   //Here we can use the server response to tell us if there's already
   //a timer running
   if(response.timerRunning){
      secondsToCountDown = response.secondsRemaining;
   }
   //Now kickoff the front-end timer
   function countdown(){
      //Add code here to display stuff to the screen, etc
      if(secondsToCountDown !== 0){
         secondsToCountDown--;
         setTimeout(countdown, 1000);
      }
   };
   if(initialLoad){
      if(response.timerRunning) countdown();
   } else {
      countdown();
   }
};

//Click handler, assuming you use jQuery
$('#myActivityButton').on('click', function(){ 
   $.ajax({
      url: 'https://...',
      type: 'POST',
      //Grabs the time of the click and sends it off to the server
      data: { currentTime: new Date() },
      success: function(response){
         restoreAndStartTimer(response, false);
      }
   });
});

$(function(){
   //On document ready
   //This should be wrapped as a function to avoid repetition, but for the sake of
   //expediency using this editor...
   $.ajax({
      url: 'https://...',
      type: 'POST',
      data: { currentTime: new Date() },
      //If a user had reloaded the page while a timer was running, it will get picked
      //up here, otherwise it does nothing.
      success: function(response){
         restoreAndStartTimer(response, true);
      }
   });
});

至於后端,您將有一些作為后台線程運行的方法。 該線程將從前端發送的初始時間戳中獲取時間,並根據狀態返回以下任何響應:

  1. 鑒於時間間隔尚未完成, response.timerRunning = trueresponse.secondsRemaining = #ofSeconds
  2. 當時間間隔最終完成時, response.timerRunning = false

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM