简体   繁体   中英

How to use Timer and SwingWorker in an Eclipse Plugin?

I'm developing an Eclipse plugin that will contribute to the GUI with a view.

The view is updated with informations from a versioning system when the user selects a folder or a file in the workspace.

In order to avoid collecting data everytime the user goes through the project subfolders and files, I need to wait for 3 seconds in order to be sure that the file or folder is the one of interest.

I'm currently doing this using a Swing Timer.

This is ok for small amount of data, but for large amount of data the GUI blocks, waiting for the timer to execute the update function.

I know for this kind of task I can use SwingWorker but I can't figure out how to delay the task and to restart the delay when needed.

Can anyone give me a solution on how to correctly solve this problem ?

Here is my current code:

  public void resetTimerIfNeeded()
    {
        if(timer.isRunning())
            timer.restart();
        else
            timer.start();
    }


    public void timer()
    {
        selectionTimer = new Timer(3000, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                // TODO Auto-generated method stub


                Display.getDefault().syncExec(new Runnable(){
                    @Override
                    public void run()
                    {               
                        updateView();
                        selectionTimer.stop();                  
                    }
                }); 
            }
        });
    }

Since Eclipse uses SWT rather than Swing it is best to avoid using Swing code.

You can run code in the UI thread after a delay using UIJob , something like:

UIJob job = new UIJob("Job title") {
        @Override
        public IStatus runInUIThread(IProgressMonitor monitor) {

            updateView();

            return Status.OK_STATUS;
        }
    };

job.schedule(3000);

Alternatively you can use Display.timerExec :

Display.getDefault().timerExec(3000, new Runnable(){
         @Override
         public void run()
         {               
           updateView();
         }
    });

Schedule it as a Job instead: https://eclipse.org/articles/Article-Concurrency/jobs-api.html . Use a UIJob if the entirety of what it's doing is interacting with the UI. The cancel/schedule and sleep/wakeUp methods will be of interest , see http://help.eclipse.org/luna/topic/org.eclipse.platform.doc.isv/reference/api/org/eclipse/core/runtime/jobs/Job.html for the JavaDoc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM