所以在前端主页中,有一个可以打开和关闭的开关。交换机的状态码可以使用Ajax发送到后端。
现在,当开关打开时,我想让后端方法继续运行,我定义如下:
public static void foo {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
while(true) {
try {
Thread.sleep(8000);
ArticleDAO.addNewArticles();
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
thread.start();
}而当切换关闭时,我想要方法或线程被终止。
JSP页面中的Ajax代码如下所示:
$("#switcher").on("switchChange.bootstrapSwitch", function(e, state) {
if (state == true) {
$(function() {
$.ajax({
type: "POST",
url: "http://localhost:8080/wx/admin/toggle_state.html",
data: {
stateCode: 1
},
success: function(data) {
alert("Switched to auto mode");
},
error: function() {
alert("Something went wrong!!");
}
});
});
} else if (state == false) {
$(function() {
$.ajax({
type: "POST",
url: "http://localhost:8080/wx/admin/toggle_state.html",
data: {
stateCode: 0
},
success: function(data) {
alert("Switched to manual mode");
},
error: function() {
alert("Something went wrong!!");
}
});
});
} else {
alert("Something went wrong!!");
}
});这里是弹簧控制器:
@RequestMapping(value = "admin/toggle_state.html", method = RequestMethod.POST)
@ResponseBody
public String toggleState(@RequestParam Integer stateCode) throws Exception {
if (stateCode == 1) {
/*
EXECUTE THE FOO METHOD RIGHT HERE
*/
System.out.println("Switched to auto mode.");
} else if (stateCode == 0) {
// TERMINATE THE METHOD / THREAD HERE
}
return "";
}那么实现这一目标的推荐方法是什么?它实际上并不难,但我不知道如何开始和终止我的情况下的线程。我能想到的一种方法是将交换机的状态代码存储到数据库,并使方法在线程中每次运行该方法时检查数据库。但这似乎不是一个好的解决方案。有任何想法吗?提前致谢!!