]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.utils.thread/src/org/simantics/utils/threads/ExecutorWorker.java
e63b304e9e27c7df7ca58f2efbea9ac7daa3a2ee
[simantics/platform.git] / bundles / org.simantics.utils.thread / src / org / simantics / utils / threads / ExecutorWorker.java
1 /*******************************************************************************
2  * Copyright (c) 2007, 2010 Association for Decentralized Information Management
3  * in Industry THTH ry.
4  * All rights reserved. This program and the accompanying materials
5  * are made available under the terms of the Eclipse Public License v1.0
6  * which accompanies this distribution, and is available at
7  * http://www.eclipse.org/legal/epl-v10.html
8  *
9  * Contributors:
10  *     VTT Technical Research Centre of Finland - initial API and implementation
11  *******************************************************************************/
12 /*
13  *
14  * @author Toni Kalajainen
15  */
16 package org.simantics.utils.threads;
17
18 import java.util.concurrent.Callable;
19 import java.util.concurrent.ScheduledFuture;
20 import java.util.concurrent.ScheduledThreadPoolExecutor;
21 import java.util.concurrent.TimeUnit;
22
23
24 public class ExecutorWorker {
25         
26         private static ExecutorWorker instance;
27         
28         static class DelayedExecution implements Comparable<DelayedExecution> {
29                 Executable executable;
30                 long executionTime;
31                 @Override
32                 public int compareTo(DelayedExecution o) {
33                         if (o.executionTime<executionTime) return -1;
34                         if (o.executionTime>executionTime) return 1;
35                         return 0;
36                 }
37         }
38
39         public static ExecutorWorker getInstance()
40         {
41                 if (instance == null)
42                         instance = new ExecutorWorker();
43                 return instance;
44         }
45         
46         ExecutorWorker() {              
47         }       
48
49         ScheduledThreadPoolExecutor pool = new ScheduledThreadPoolExecutor(1);
50         
51         public synchronized ScheduledFuture<Object> timerExec(final Executable executable, int delay)
52         {
53                 Callable<Object> c = new Callable<Object>() {
54                         @Override
55                         public Object call() throws Exception {
56                 // FIXME: executable.runnable gets called twice!
57                                 ThreadUtils.asyncExec(executable.threadAccess, executable.runnable);
58                                 //executable.runnable.run();
59                                 return null;
60                         }
61                 };              
62                 return pool.schedule(c, delay, TimeUnit.MILLISECONDS);
63         }
64
65 }