简体   繁体   中英

The @Scheduled Annotation in Spring

I created a chat using the vaadin framework 14 and spring boot. It works well, only I need to create a timer for it. I created a timer, but I was told that this is wrong. I created a timer using Java, this is wrong. I need to use (The @Scheduled Annotation in Spring) in my "MainView" class. So that he calls (api/unread) every second.

I previously create a class "TimerConfig". But they said it was wrong

public class TimerConfig {


    @Autowired
    MessageServiceImpl messageService;

    @Bean
    public TimerTask timer () {
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                messageService.getAllMessages();
            }

        };
        Timer timer = new Timer();
        timer.schedule(timerTask, 1000, 1000);
        return timerTask;
    }
}

Need in this class "MainView" create (@Scheduled Annotation in Spring) so that the timer calls (api/unread) every second

MainView class

@StyleSheet("frontend://styles/styles.css")
@Route
@PWA(name = "Vaadin MessagesInfoManager", shortName = "Vaadin MessagesInfoManager")
@Push
public class MainView extends VerticalLayout {
    private final MessagesInfoManager messagesInfoManager;
    private final RestService restService;
    private String username;

    @Autowired
    public MainView(RestService restService) {
        this.messagesInfoManager = MessageConfigurator.getInstance().getChatMessagesInfoManager();
        addClassName("main-view");
        setSizeFull();
        setDefaultHorizontalComponentAlignment(Alignment.CENTER);

        H1 header = new H1("Vaadin Chat");
        header.getElement().getThemeList().add("dark");

        add(header);

        askUsername();
        this.restService = restService;
    }

    private void askUsername() {
        HorizontalLayout layout = new HorizontalLayout();
        TextField usernameField = new TextField();
        Button startButton = new Button("Start chat");

        layout.add(usernameField, startButton);

        startButton.addClickListener(click -> {
            username = usernameField.getValue();
            remove(layout);
            showChat(username);
        });

        add(layout);
    }

    private void showChat(String username) {
        MessageList messageList = new MessageList();

        List<Message> lasts = restService.getLast();
        for (Message message : lasts) {
            messageList.add(new Paragraph(message.getFrom() + ": " + message.getMessage()));
        }

        add(messageList, createInputLayout(username, messageList));
        expand(messageList);
    }

    private Component createInputLayout(String username, MessageList messageList) {
        HorizontalLayout layout = new HorizontalLayout();
        layout.setWidth("100%");

        TextField messageField = new TextField();
        messageField.addKeyDownListener(Key.ENTER, keyDownEvent -> sender(messageField, messageList));
        Button sendButton = new Button("Send");
        sendButton.addThemeVariants(ButtonVariant.LUMO_PRIMARY);

        layout.add(messageField, sendButton);
        layout.expand(messageField);

        messageField.addFocusListener(event -> {
            for (Message message : messagesInfoManager.getMessagesByUI(getUI())) {
                if (!message.getFrom().equals(username)) {
                    message.setUnread(false);
                    this.restService.updateMessage(message.getId(), message);
                }
            }
        });

        sendButton.addClickListener(click -> sender(messageField, messageList));
        messageField.focus();

        return layout;
    }

    private void sender(TextField textField, MessageList messageList) {
        Message message = new Message(username, textField.getValue());
        message = restService.saveMessage(message);
        messagesInfoManager.updateMessageUIInfo(new MessageInfo(messageList, message, this));
        textField.clear();
        textField.focus();
    }
}

My Rest Controller

public class RestController {

    @Autowired

    TimerTask timerTask;

    @Resource
    private final MessageService messageService;

    public RestController(MessageService messageService) {
        this.messageService = messageService;
    }



    @GetMapping("/api/unread")
    public void getUnreadMessages() {

        timerTask.run(); // it's wrong 
    }

My github https://github.com/fallen3019/vaadin-chat

Enable Scheduling

You can enable scheduling simply by adding the @EnableScheduling annotation to the main application class or any configuration class.

Scheduling Tasks

Scheduling a task is as simple as annotating a method with @Scheduled annotation.

In the below example, execute() method is scheduled to run every second. execute() method will invoke the desired service method.

public class MainView extends ... {

    // Existing Code

    @Autowired
    private MessageServiceImpl messageService;

    @Scheduled(fixedRate = 1000)
    public void execute() {
        messageService.getAllMessages();
    }

}

Types of Scheduling

  1. Scheduling with fixed rate

    execute() method can be scheduled to run with a fixed interval using fixedRate parameter.

     @Scheduled(fixedRate = 2000)
  2. Scheduling with fixed delay

    execute() method can be scheduled to run with a fixed delay between the completion of the last invocation and the start of the next, using fixedDelay parameter.

     @Scheduled(fixedDelay = 2000)
  3. Scheduling with initial delay and fixed rate / fixed delay

    initialDelay parameter with fixedRate and fixedDelay to delay the first execution.

     @Scheduled(fixedRate = 2000, initialDelay = 5000)
     @Scheduled(fixedDelay= 2000, initialDelay = 5000)
  4. Scheduling with cron

    execute() method can be scheduled to run based on cron expression using cron parameter.

     @Scheduled(cron = "0 * * * * *")

keep the @Scheduled Anno on top of the getAllMessages() method serviceImpl

public class MessageServiceimpl {
 @Scheduled(fixedDelay = 1500000)// 25 min
public void getAllMessages(){
---------------
--- your implementations 
--------------- 
}
}
public class MainView extends VerticalLayout {

@Autowired
MessageServiceImpl messageService;

---- 
---- your code here----
----

@Scheduled(fixedRate = 1000)   (OR @Scheduled(cron = "0 * * * * *"))
void getMessagesBySchedule(){
    messageService.getAllMessages();
{

This code work every second

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM