有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java是Spring中的@Scheduled注释

我使用vaadin framework 14和spring boot创建了一个聊天室。它工作得很好,只是我需要为它创建一个计时器。我创建了一个计时器,但有人告诉我这是错误的。我用Java创建了一个计时器,这是错误的。我需要在我的“MainView”类中使用(Spring中的@Scheduled注释)。这样他就可以每秒调用(api/未读)

我之前创建了一个类“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”创建(@Scheduled Annotation in Spring),以便计时器每秒调用(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 
    }

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


共 (3) 个答案

  1. # 1 楼答案

    将@Scheduled Anno放在getAllMessages()方法serviceImpl的顶部

    public class MessageServiceimpl {
     @Scheduled(fixedDelay = 1500000)// 25 min
    public void getAllMessages(){
           -
     - your implementations 
           - 
    }
    }
    
  2. # 2 楼答案

    public class MainView extends VerticalLayout {
    
    @Autowired
    MessageServiceImpl messageService;
    
       
       your code here  
      
    
    @Scheduled(fixedRate = 1000)   (OR @Scheduled(cron = "0 * * * * *"))
    void getMessagesBySchedule(){
        messageService.getAllMessages();
    {
    

    这个代码每秒钟工作一次

  3. # 3 楼答案

    启用调度

    只需将@EnableScheduling注释添加到主应用程序类或任何配置类,即可启用调度

    安排任务

    调度任务就像用@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 * * * * *")