Java 在SpringWeb应用程序中使用计时器跟踪用户操作
我正在SpringHibernate中开发一个管理应用程序,其中需要实现一个计时器系统 用例Java 在SpringWeb应用程序中使用计时器跟踪用户操作,java,javascript,spring,jakarta-ee,timer,Java,Javascript,Spring,Jakarta Ee,Timer,我正在SpringHibernate中开发一个管理应用程序,其中需要实现一个计时器系统 用例 用户单击UI(jsp)上的活动或事件。计时器启动后,在UI上显示倒计时。只有在规定的计时器计数结束后,用户才能再次执行该事件 我需要在数据库中保留时间,因为如果用户关闭浏览器,服务器中的计时器计数应该继续。就像我们在基于网络的社交媒体游戏中遇到的那样 我在网上搜索了一个解决方案,但没有找到任何结果。我尝试了Spring计划,但似乎没有解决问题,而且它有很多限制 有人能给我提出解决办法吗?谢谢你回答这个问
有人能给我提出解决办法吗?谢谢你回答这个问题,我假设如下:
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=#of seconds
假设时间间隔尚未完成response.timerRunning=false
时间间隔最终完成时充其量,您可以尝试
window.onbeforeuload
以某种方式通知服务器,您的浏览器窗口正在关闭。