[英]Using a timer for tracking user action in a Spring web application
我正在Spring Hibernate中開發一個管理應用程序,其中我需要實現一個計時器系統。
使用案例
用戶單擊UI(jsp)上的活動或事件。 計時器啟動,它在UI上顯示倒計時。 只有在規定的計時器計數結束后,用戶才能再次執行該事件。
我需要將時間保留在數據庫中,因為如果用戶關閉瀏覽器,計時器計數應在服務器中繼續。 就像我們在基於網絡的社交媒體游戲中遇到的方式一樣。
我在網上搜索了一個解決方案,但沒有發現任何問題。 我嘗試了Spring Scheduling,但似乎無法解決問題,而且有很多局限性。
誰能建議我任何解決方案? 謝謝
為了回答這個問題,我將假設以下內容:
基本思想是,您向服務器發送日期戳,在前端開始倒計時,並且只要有互動可以再次嘗試該活動,就詢問服務器(相同的后台任務)時間是否間隔已完成。
下面的解決方案只是一個開始,絕不是管理這種交互所需要的完整版本。
在前端,您可以想象執行以下操作:
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);
}
});
});
至於后端,您將有一些作為后台線程運行的方法。 該線程將從前端發送的初始時間戳中獲取時間,並根據狀態返回以下任何響應:
response.timerRunning = true
和response.secondsRemaining = #ofSeconds
response.timerRunning = false
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.