package com.fs.app.websocket.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.websocket.Session;
import java.io.IOException;
import java.util.Collection;

@Slf4j
@Component
public class Task {

    @Scheduled(cron = "0 0/5 * * * ?")
//    @Scheduled(cron = "0/5 * * * * ?")
    public void addUser() {
        Collection<Session> values = WebSocketServer.sessionPools.values();
        values.forEach(session -> {
            sendMessage(session, "{\"cmd\":\"addUser\"}");
        });
    }
    @Scheduled(cron = "0 0/5 * * * ?")
//    @Scheduled(cron = "0/5 * * * * ?")
    public void checkUser() {
        Collection<Session> values = WebSocketServer.sessionPools.values();
        values.forEach(session -> {
            sendMessage(session, "{\"cmd\":\"checkUser\"}");
        });
    }
    public void sendMessage(Session session, String message) {
        if(session != null){
            synchronized (session) {
                try {
                    session.getBasicRemote().sendText(message);
                } catch (IOException e) {
                    log.error("发送数据失败！");
                }
            }
        }
    }
}
