我正在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
时间间隔最终完成时本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句