Call function every x time without blocking the GUI Java

后端 未结 3 1773
余生分开走
余生分开走 2021-01-23 02:31

I have a class caled ItemGUI which is handling everything related with the user interface. The user, is able to add some links, which are the items, so when he inserts a link an

3条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-23 02:56

    You can use a Timer to schedule a repeating task.

    Corresponding to each Timer object is a single background thread that is used to execute all of the timer's tasks, sequentially

    Something along the lines of this code should do the trick.

    Timer timer = new Timer();
    TimerTask task = new TimerTask(){
        public void run() {
            getPrice(); //your task
        }
    };
    
    timer.schedule(task, 0, 5000); //first is delay, second is repeat period
    
    ...
    // on button click, simple cancel the task
    task.cancel()
    

提交回复
热议问题