I have an application where I need to access a webservice every minute. I was going to use a thread for this, however if the user enters anything, the 'timer' needs to be delayed. I don't quite understand how to implement this in java
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
take a look at these examples of wait() and notify() at programcreek.com, do you know the concept of wait and notify?
回答2:
Personally here is how I deal with it: I declare 2 classes that will give you the functionality of function call after every given milliseconds.
In a new interface:
public interface TickListener {
public void tick();
public void tick(Exception e);
}
And in another class
public class TickManager {
public static final int STATE_TICK_ONCE = 0;
public static final int STATE_TICK_NONSTOP = 1;
public static final int STATE_TICK_NONE = 2;
int state, delay;
Thread t;
TickListener[] listeners;
long tickCount;
public TickManager(){
this(TickManager.STATE_TICK_NONE);
}
public TickManager(int state){
this(state,1000);
}
public TickManager(int state, int d){
this(state,d,null);
}
public TickManager(int state, int d, TickListener[] t){
this.state = state;
delay = d;
listeners = t;
tickCount=0;
if(state!=2){
startTicking(state);
}
}
public void startTicking(int s){
tickCount = 0;
state=s;
t = new Thread(new Runnable() {
@Override
public void run() {
while (state!=TickManager.STATE_TICK_NONE) {
tickCount++;
try {
Thread.sleep(delay);
} catch (Exception e) {
process(e);
stopTicking();
}
process();
if (state == TickManager.STATE_TICK_ONCE && tickCount == 1) {
stopTicking();
}
}
}
});
t.start();
}
public void process(){
if(listeners!=null){
for(TickListener l : listeners){
l.tick();
}
}
}
public void process(Exception e){
if(listeners!=null){
for(TickListener l : listeners){
l.tick(e);
}
}
}
public void stopTicking(){
state = TickManager.STATE_TICK_NONE;
t=null;
}
public int getState() {
return state;
}
public int getDelay() {
return delay;
}
public Thread getThread() {
return t;
}
public TickListener[] getListeners() {
return listeners;
}
public long getTickCount() {
return tickCount;
}
public void setState(int state) {
this.state = state;
}
public void setTickCount(long tickCount) {
this.tickCount = tickCount;
}
public void setDelay(int delay) {
this.delay = delay;
}
public void addTickListener(TickListener t){
if(listeners!=null){
int l = listeners.length;
TickListener[] tl = new TickListener[l+1];
System.arraycopy(listeners, 0, tl, 0, l);
tl[l] = t;
listeners=tl;
}
else{
listeners=new TickListener[1];
listeners[0]=t;
}
}
}
All you have to do is to create an object of TickManager
, register a TickListener
in it and call startTicking()
on it. The delay is set via constructor also.
Just ensure that you do not change the delay time while it is ticking. It can be checked by calling getState()
function and comparing it to the class constants. If it is, then you must stop it, change the delay and start it again.