簡體   English   中英

Spring中的@Scheduled注解

[英]The @Scheduled Annotation in Spring

我使用 vaadin framework 14 和 spring boot 創建了一個聊天。 它運行良好,只是我需要為它創建一個計時器。 我創建了一個計時器,但有人告訴我這是錯誤的。 我使用 Java 創建了一個計時器,這是錯誤的。 我需要在我的“MainView”類中使用(Spring 中的 @Scheduled Annotation)。 所以他每秒調用(api/unread)。

我以前創建了一個類“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;
    }
}

需要在此類“MainView”中創建(Spring 中的@Scheduled Annotation),以便計時器每秒調用(api/unread)

主視圖類

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

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

啟用調度

您只需將@EnableScheduling注釋添加到主應用程序類或任何配置類即可啟用調度。

調度任務

調度任務就像使用@Scheduled注釋來注釋方法一樣簡單。

在下面的示例中, execute()方法被安排為每秒運行一次。 execute()方法將調用所需的服務方法。

public class MainView extends ... {

    // Existing Code

    @Autowired
    private MessageServiceImpl messageService;

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

}

調度類型

  1. 固定費率調度

    可以使用fixedRate參數安排execute()方法以固定間隔運行。

     @Scheduled(fixedRate = 2000)
  2. 固定延遲調度

    可以使用fixedDelay參數安排execute()方法在上次調用完成和下一次調用開始之間以固定延遲運行。

     @Scheduled(fixedDelay = 2000)
  3. 具有初始延遲和固定速率/固定延遲的調度

    帶有fixedRatefixedDelay initialDelay參數來延遲第一次執行。

     @Scheduled(fixedRate = 2000, initialDelay = 5000)
     @Scheduled(fixedDelay= 2000, initialDelay = 5000)
  4. 使用 cron 進行調度

    可以使用cron參數根據 cron 表達式安排execute()方法運行。

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

將 @Scheduled Anno 放在 getAllMessages() 方法 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();
{

這段代碼每秒都在工作

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM