启动类上加 @EnableScheduling 注解
定时任务类上加@Component
定时方法上加@Scheduled
webSocket发送消息管理bean
定时任务方法
@Async
@Scheduled(cron = "* * * * * *")// 每秒执行一次定时发送websocket消息
public void WebSocketTime(){
// 连接完成后触发定时器来定时发送考试倒计时
webSocketMessageSender.sendObject(UserTypeEnum.ADMIN.getValue(),"demo-message-receive",examTimes);
}
websocket定时任务发送消息
vue前端连接服务器websocket
接收服务端websocket广播(群发)消息
代码:
1.
import {getNowDateTime} from "../../utils/ruoyi";
import {getAccessToken} from "../../utils/auth";
2.
created() {
const wsUrl = process.env.VUE_APP_BASE_API + "/infra/ws" + '?token=' + getAccessToken();
this.url = wsUrl.replace("http", "ws");
// 建立连接
this.ws = new WebSocket(this.url);
// 监听 open 事件
this.ws.onopen = (event) => {
this.content = this.content + "\n**********************连接开始**********************\n";
};
// 监听 message 事件
this.ws.onmessage = (event) => {
try {
const data = event.data;
// 1. 收到心跳
if (data === 'pong') {
return;
}
// 2.1 解析 type 消息类型
const jsonMessage = JSON.parse(data)
const type = jsonMessage.type;
const content = JSON.parse(jsonMessage.content);
if (content.indexOf("s") == -1) {
this.show = true;
} else {
this.show = false;
}
this.endTime = content;
if (this.endTime == "00:00:00") {
this.$store.dispatch('LogOut').then(() => {
location.href = getPath('/index');
})
this.$message.error("考试结束!")
// clearInterval(timer);
// window.location.reload();
}
if (!type) {
this.$modal.msgError('未知的消息类型:' + data);
return;
}
// 2.2 消息类型:demo-message-receive
if (type === 'demo-message-receive') {
const single = content.single;
this.content = this.content + "接收时间:" + getNowDateTime() + "\n" +
`【${single ? '单发' : '群发'}】用户编号(${content.fromUserId}):${content.text}` + "\n";
return;
}
// 2.3 消息类型:notice-push
if (type === 'notice-push') {
this.content = this.content + "接收时间:" + getNowDateTime() + "\n" + `【系统通知】:${content.title}` + "\n";
return;
}
this.$modal.msgError('未处理消息:' + data);
} catch (error) {
this.$modal.msgError('处理消息发生异常:' + event.data);
console.error(error);
}
};
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function () {
if (this.ws) {
this.ws.close();
this.ws = null;
}
}
}
功能结果:
考试时间统一倒计时