Paho-Mqtt Periodic Publications approaches - java

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);

Related

How to start timer after make cancelling timer?

I had using timer I make cancel or stop timer on button click and then I want to start again timer on click start button.How can doing start timer after cancelling timer?
timerLoop = new Timer();
hourlyTaskLoop = new TimerTask() {
#Override
public void run() {
}
};
timerLoop.schedule(hourlyTaskLoop, 0l, 1000);
stop timer
timerLoop.cancel();
hourlyTaskLoop.cancel();
I hope this could help you
Stopwatch stopwatch = Stopwatch.createStarted();
void startThreadUpdateTimer(){}
Timer T = new Timer();
T.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
String workingTime = "Your effort is " + sw.toString() +
" till now for the day";
}
});
}
}, 1000, 1000);
}
public void pause(){
if(stopwatch.isRunning()){
stopwatch.stop();
}
}
public void resume(){
if(!stopwatch.isRunning()){
stopwatch.start();
}
}

AndroidStudio - How to add a loop and delay (in minutes)

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

Threads running at specific time intervals for a specific time in JAVA

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);

Timer in java with Threads

I want to print this line:
System.out.println(Runtime.getRuntime().freeMemory());
every second. How to do it?
public class Hilo implements Runnable{
Thread t;
String nombre;
public Hilo() {
t = new Thread(this,"Hilo1");
t.start();
}
#Override
public void run() {
System.out.println(Runtime.getRuntime().freeMemory());
}
}
Use a java.util.Timer object.
A facility for threads to schedule tasks for future execution in a background thread. Tasks may be scheduled for one-time execution, or for repeated execution at regular intervals.
timer.schedule(new TimerTask() {
#Override
public void run() {
System.out.println(Runtime.getRuntime().freeMemory());
}
}, 0, 1000);
Another way to do it
ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor();
ses.scheduleAtFixedRate(new Runnable() {
#Override
public void run() {
System.out.println(Runtime.getRuntime().freeMemory());
}
}, 0, 1, TimeUnit.SECONDS);
ses.shutdown();
Differences between java.util.timer and ScheduledExecutorService
ScheduledThreadPoolExecutor are not sensitive to changes in the system clock but Timer is.
Timer has only one execution thread, so long-running task can delay other tasks.
ScheduledThreadPoolExecutor can be configured with any number of threads
By using below code you can print that want after every second
timer.schedule(new TimerTask() {
#Override
public void run() {
System.out.println(Runtime.getRuntime().freeMemory());
}
}, 0, 1000);
}

How to have two timers for Java game applet

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();
}
}

Categories