Spring 中的 @Scheduled 注解

The @Scheduled Annotation in Spring

我使用 vaadin 框架 14 和 spring 引导创建了一个聊天。它运行良好,只是我需要为它创建一个计时器。我创建了一个计时器,但有人告诉我这是错误的。我使用 Java 创建了一个计时器,这是错误的。我需要在我的 "MainView" class 中使用(Spring 中的 @Scheduled 注释)。以至于他每秒都调用(api/unread)。

我之前创建了一个 class "TimerConfig"。但他们说这是错误的

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;
    }
}

需要在这个class"MainView"中创建(@Scheduled Annotation inSpring)以便定时器每秒调用(api/unread)

主视图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();
    }
}

我的休息控制器

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 
    }

我的githubhttps://github.com/fallen3019/vaadin-chat

将 @Scheduled Anno 保持在 getAllMessages() 方法 serviceImpl 之上

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

启用计划

您只需将 @EnableScheduling 注释添加到主应用程序 class 或任何配置 class。

即可启用调度

计划任务

安排任务就像用 @Scheduled 注释注释方法一样简单。

在下面的示例中,execute() 方法每秒调度到 运行。 execute() 方法将调用所需的服务方法。

public class MainView extends ... {

    // Existing Code

    @Autowired
    private MessageServiceImpl messageService;

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

}

调度类型

  1. 固定费率安排

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

    @Scheduled(fixedRate = 2000)
    
  2. 固定延迟安排

    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. 使用初始延迟和固定速率/固定延迟进行调度

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

    @Scheduled(fixedRate = 2000, initialDelay = 5000)
    
    @Scheduled(fixedDelay= 2000, initialDelay = 5000)
    
  4. 使用 cron 计划

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

    @Scheduled(cron = "0 * * * * *")
    
public class MainView extends VerticalLayout {

@Autowired
MessageServiceImpl messageService;

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

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

此代码每秒运行一次