1

I want to use the below mentioned operations in JAVA for android development.

  1. For 30 Seconds ,Run a Function F1() every 1 second (resulting in 30 F1 calls).
  2. Run a Thread t1 forever

The above steps should execute sequentially. I Have tried with ExecutorServicebut with no success.

This is my code for reference

final Handler h = new Handler();
final int delay = 1000; //milliseconds
ExecutorService executor = Executors.newFixedThreadPool(1);

Thread t1 = new Thread(new Runnable() {
    @Override
    public void run() {
        F1();
    }
});

for(int i=0;i<30;i++){
    executor.submit(t1);
    try {
        TimeUnit.SECONDS.sleep(1);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

executor.shutdown();
//Step 2 (THe Second Thread)

h.postDelayed(new Runnable() {
    public void run() {
        AnotherFunction()
        h.postDelayed(this, delay);
    }
}, delay);
the-ginger-geek
  • 7,041
  • 4
  • 27
  • 45
shikhar bansal
  • 1,629
  • 2
  • 21
  • 43

3 Answers3

1

Generally, ExecutorService is more preferable for such operations. Here is a good post describing the differences and features of Timer and ExecutorService.

As for your question directly - it can be implemented in such way:

// here are Runnables with test logic
Runnable foo = new Runnable() {
    @Override
    public void run() {
        Log.d(">>>", "foo");
        onTaskFinished();
    }
};

Runnable longRunning = new Runnable() {
    @Override
    public void run() {
        try {
            Log.d(">>>", "longRunning started");
            Thread.sleep(5000);
            Log.d(">>>", "longRunning finished");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
};

// and here is valuable logic
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
ScheduledFuture<?> schedulerHandler;
volatile AtomicInteger tasksNum = new AtomicInteger(0);

private synchronized void onTaskFinished(){
    if(tasksNum.incrementAndGet() >= 30){
        scheduler.execute(new Runnable() {
            @Override
            public void run() {
                schedulerHandler.cancel(true);
            }
        });
        scheduler.execute(longRunning);
    }
}

And then to start operation just invoke this command:

schedulerHandler = scheduler.scheduleAtFixedRate(foo, 0, 1, TimeUnit.SECONDS);
Community
  • 1
  • 1
DmitryArc
  • 4,757
  • 2
  • 37
  • 42
0

You may consider using the java.util.Timer and java.util.TimerTask classes

erosb
  • 2,943
  • 15
  • 22
0

If you're doing what I think you're doing you can do as @erosb hinted, use Timer and TimerTask to schedule method executions at a fixed rate.

The following should work for you.

final int DELAY_BEFORE_START = 0;
final int RATE = 1000; 

Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
    @Override
    public void run() {
        F1();
    }
}, DELAY_BEFORE_START, RATE);
the-ginger-geek
  • 7,041
  • 4
  • 27
  • 45