I have the following void:
public void onClick(View v)
{
PostDataTask postDataTask = new PostDataTask();
postDataTask.execute(URL,textView3.getText().toString(),textView5.getText().toString(),textView12.getText().toString(),textView13.getText().toString(),textView14.getText().toString(),textView7.getText().toString(),textView15.getText().toString());
}
And I want to loop the "postDataTask.execute(...)" so it will be executed every 30 minutes for 24 hours (so executing 48 times in total). Can someone help me with this?
*EDIT
So I used the 1st suggestion given, but it only runs 1 time 60 seconds. Is it because it have the class in onCreate? :
#Override
protected void onCreate(Bundle savedInstanceState) {
final PostDataTask postDataTask = new PostDataTask();
final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
final Runnable exec = new Runnable() {
public void run() {
postDataTask.execute(URL, textView3.getText().toString(), textView5.getText().toString(), textView12.getText().toString(), textView13.getText().toString(), textView14.getText().toString(), textView7.getText().toString(), textView15.getText().toString());
}
};
final ScheduledFuture execHandle = scheduler.scheduleAtFixedRate(exec, 60, 60, SECONDS);
scheduler.schedule(new Runnable() {
public void run() {
execHandle.cancel(true);
}
}, 60 * 60, SECONDS);
ScheduledExecutorService can do the thing.
Usage Example
Here is a class with a method that sets up a ScheduledExecutorService to beep every ten seconds for an hour:
import static java.util.concurrent.TimeUnit.*;
class BeeperControl {
private final ScheduledExecutorService scheduler =
Executors.newScheduledThreadPool(1);
public void beepForAnHour() {
final Runnable beeper = new Runnable() {
public void run() { System.out.println("beep");
};
final ScheduledFuture beeperHandle =
scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS);
scheduler.schedule(new Runnable() {
public void run() { beeperHandle.cancel(true); }
}, 60 * 60, SECONDS);
}
}}
Code from ScheduledExecutorService documentation
Related
My task is that if within 90 seconds no MotionEvent occurs, there are no clicks on the buttons, then a certain method is called. How can I call a method if within 90 seconds there is no action?
There is a number of alternative ways to do this
Now currently it is running every 2 min change accordingly
ScheduledExecutorService scheduleTaskExecutor = Executors.newScheduledThreadPool(5);
// This schedule a runnable task every 2 minutes
scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
public void run() {
doSomethingUseful();
}
}, 0, 2, TimeUnit.MINUTES); // change accordingly
OR
private Handler handler = new Handler();
private Runnable runnable = new Runnable() {
#Override
public void run() {
yourfunction();
handler.postDelayed(this, 1000);
}
};
//Start
handler.postDelayed(runnable, 1000);
What is the best way to publish safely data periodically ?
First approach:
while(true){
Thread.sleep(1000);
//pub
}
second:
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
//pub
}
}
third:
ScheduledExecutorService ses = Executors.newScheduledThreadPool(1);
ses.scheduleAtFixedRate(new Runnable() {
public void run() { //pub }
}, 0, 3, TimeUnit.SECONDS);
I want to use the below mentioned operations in JAVA for android development.
For 30 Seconds ,Run a Function F1() every 1 second (resulting in 30 F1 calls).
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);
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);
You may consider using the java.util.Timer and java.util.TimerTask classes
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);
I require two timers. One to run the game e.g move objects, and perform checks and another as a countdown timer. I have tried the following:
Timer countdownTimer = new Timer(1000,this);
Timer gameTimer = new Timer(30,this);
public void init()
{
this.actionPerformed(this); //add action listener to content pane
}
#Override
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == gameTimer)
{
// control the game
}
if(e.getSource() == countdownTimer)
{
//decremenet the timer
}
}
However this returns a Null pointer exception when I try to run the applet. How do I properly distinguish each timer from the other and perform the desired actions at each timer tick. Thanks
I'm assuming you're using the javax.swing.Timer class?
this.actionPerformed(this); does not seem right, as your applet is not an ActionEvent.
Besides, you should start the timers in the init() method:
public class GameApplet extends Appel implements ActionListener
public void init()
{
countdownTimer = new Timer(1000,this);
gameTimer = new Timer(30,this);
countdownTimer.start();
gameTimer.start();
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == gameTimer) {
// control the game
}
if(e.getSource() == countdownTimer) {
//decremenet the timer
}
}
}
Check the Timer javadoc that also redirects to the Java tutorial about Timers.
Use ScheduledExecutorService. It is more efficient than timer. To see its effect run following code.
class GameControl {
private final ScheduledExecutorService scheduler =
Executors.newScheduledThreadPool(1);
public void beepForGame() {
final Runnable beeper = new Runnable() {
#Override
public void run() {
System.out.println("Game");
}
};
final ScheduledFuture<?> beeperHandle =
scheduler.scheduleAtFixedRate(beeper, 30, 30, SECONDS);
scheduler.schedule(new Runnable() {
#Override
public void run() {
beeperHandle.cancel(true);
}
}, 60 * 60, SECONDS);
}
public void beepCountDown() {
final Runnable beeper = new Runnable() {
#Override
public void run() {
System.out.println("count down");
}
};
final ScheduledFuture<?> beeperHandle =
scheduler.scheduleAtFixedRate(beeper, 1, 1, SECONDS);
scheduler.schedule(new Runnable() {
#Override
public void run() {
beeperHandle.cancel(true);
}
}, 60 * 60, SECONDS);
}
public static void main(String[] args) {
GameControl bc=new GameControl();
bc.beepCountDown();
bc.beepForGame();
}
}
I'm not an expert, just a beginner. So I kindly ask that you write some code for me.
If I have two classes, CLASS A and CLASS B, and inside CLASS B there is a function called funb(). I want to call this function from CLASS A every ten minutes.
You have already given me some ideas, however I didn't quite understand.
Can you post some example code, please?
Have a look at the ScheduledExecutorService:
Here is a class with a method that sets up a ScheduledExecutorService to beep every ten seconds for an hour:
import static java.util.concurrent.TimeUnit.*;
class BeeperControl {
private final ScheduledExecutorService scheduler =
Executors.newScheduledThreadPool(1);
public void beepForAnHour() {
final Runnable beeper = new Runnable() {
public void run() { System.out.println("beep"); }
};
final ScheduledFuture<?> beeperHandle =
scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS);
scheduler.schedule(new Runnable() {
public void run() { beeperHandle.cancel(true); }
}, 60 * 60, SECONDS);
}
}
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class ClassExecutingTask {
long delay = 10 * 1000; // delay in milliseconds
LoopTask task = new LoopTask();
Timer timer = new Timer("TaskName");
public void start() {
timer.cancel();
timer = new Timer("TaskName");
Date executionDate = new Date(); // no params = now
timer.scheduleAtFixedRate(task, executionDate, delay);
}
private class LoopTask extends TimerTask {
public void run() {
System.out.println("This message will print every 10 seconds.");
}
}
public static void main(String[] args) {
ClassExecutingTask executingTask = new ClassExecutingTask();
executingTask.start();
}
}
Try this. It will repeat the run() function every set minutes. To change the set minutes, change the MINUTES variable
int MINUTES = 10; // The delay in minutes
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() { // Function runs every MINUTES minutes.
// Run the code you want here
CLASSB.funcb(); // If the function you wanted was static
}
}, 0, 1000 * 60 * MINUTES);
// 1000 milliseconds in a second * 60 per minute * the MINUTES variable.
Don't forget to do the imports!
import java.util.Timer;
import java.util.TimerTask;
For more info, go here:
http://docs.oracle.com/javase/7/docs/api/java/util/Timer.html
http://docs.oracle.com/javase/7/docs/api/java/util/TimerTask.html
public class datetime {
public String CurrentDate() {
java.util.Date dt = new java.util.Date();
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentTime = sdf.format(dt);
return currentTime;
}
public static void main(String[] args) {
class SayHello extends TimerTask {
datetime thisObj = new datetime();
public void run() {
String todaysdate = thisObj.CurrentDate();
System.out.println(todaysdate);
}
}
Timer timer = new Timer();
timer.schedule(new SayHello(), 0, 5000);
}
}
Solution with Java 8
ClassB b = new ClassB();
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
Runnable task = () -> {
b.funb();
};
executor.scheduleWithFixedDelay(task, 0, 10, TimeUnit.MINUTES);