Java – runs background jobs without affecting the rest of the GUI

I'm looking for help with general methods

I have written some java code to view unread messages in my mailbox on buttonclick

Now, I want this code to run permanently in the background and check my mailbox every 2 minutes

lousy idea:

while(true)
{
checkMails();
Thread.sleep(120000);
}

The rest of the graphical interface will obviously freeze, so I think I have to play some magic in the thread

How can it be achieved?

Solution

Using javax swing. Timer or @ L_ 404_ 2@, although the latter is a bit overcorrected in this case

If this task does not modify any swing components, why not generate a separate thread, so

Thread t = new Thread(new Runnable(){
    @Override
    public void run(){
        while(!Thread.currentThread().isInterrupted()){
            //do stuff

            try{
                Thread.sleep(120000);
            }catch(InterruptedException e){
                Thread.currentThread().interrupt();
            }
        }
    }
});
t.start();

It is important to note that you may want to use Boolean values to ensure that the thread is created only once, because each click of the button will produce a new thread, which may not be what you want

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>