diff --git a/spring-websockets/pom.xml b/spring-websockets/pom.xml index ddfd512476..8f24962185 100644 --- a/spring-websockets/pom.xml +++ b/spring-websockets/pom.xml @@ -18,6 +18,11 @@ org.springframework.boot spring-boot-starter-websocket + + com.github.javafaker + javafaker + 1.0.2 + com.google.code.gson gson diff --git a/spring-websockets/src/main/java/com/baeldung/SpringBootApp.java b/spring-websockets/src/main/java/com/baeldung/SpringBootApp.java index ea2a461dfc..3a98746748 100644 --- a/spring-websockets/src/main/java/com/baeldung/SpringBootApp.java +++ b/spring-websockets/src/main/java/com/baeldung/SpringBootApp.java @@ -3,8 +3,10 @@ package com.baeldung; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; +import org.springframework.scheduling.annotation.EnableScheduling; @SpringBootApplication +@EnableScheduling public class SpringBootApp extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(SpringBootApp.class, args); diff --git a/spring-websockets/src/main/java/com/baeldung/websockets/ScheduledPushMessages.java b/spring-websockets/src/main/java/com/baeldung/websockets/ScheduledPushMessages.java new file mode 100644 index 0000000000..3e27d840d9 --- /dev/null +++ b/spring-websockets/src/main/java/com/baeldung/websockets/ScheduledPushMessages.java @@ -0,0 +1,31 @@ +package com.baeldung.websockets; + + +import com.github.javafaker.Faker; +import org.springframework.messaging.simp.SimpMessagingTemplate; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Controller; + +import java.text.SimpleDateFormat; +import java.util.Date; + +@Controller +public class ScheduledPushMessages { + + private final SimpMessagingTemplate simpMessagingTemplate; + + private final Faker faker; + + public ScheduledPushMessages(SimpMessagingTemplate simpMessagingTemplate) { + this.simpMessagingTemplate = simpMessagingTemplate; + faker = new Faker(); + } + + @Scheduled(fixedRate = 5000) + public void sendMessage() { + final String time = new SimpleDateFormat("HH:mm").format(new Date()); + simpMessagingTemplate.convertAndSend("/topic/messages", + new OutputMessage("Chuck Norris", faker.chuckNorris().fact(), time)); + } + +}