How to start timer after make cancelling timer? - java

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

Related

How to create new instance of TimerTask for Resume Button? (ERROR: TimerTask is scheduled already)

Good morning! I'm trying to do a pause button for my game, but having problems with initializing the timer task again when I want to resume the game.
I get the error "java.lang.IllegalStateException: TimerTask is scheduled already", which according to my research is because the TimerTask cannot be reused so a new instance must be created of it. I tried making a method in my MainActivity that would be used for this purpose, however, that did not work. This is what I'm working with:
public class MainActivity extends AppCompatActivity{
public FishView gameView;
//pause variables
Button pauseButton;
private boolean pauseFlag = false;
private final long animationPeriod = 600;
Timer movementTimer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
screen = findViewById(R.id.gameScreen);
gameView = new FishView(this);
screen.addView(gameView);
pauseButton = findViewById(R.id.pauseButton);
movementTimer = new Timer();
movementTimer.scheduleAtFixedRate(animationTask, 0, animationPeriod);
}
//this is the timer I want to reuse
private TimerTask animationTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
#Override
public void run() {
//set animation
int selectedFish = gameView.getSelectedFish();
if (selectedFish==1){
gameView.setSelectedFish(0);}
if (selectedFish==0){
gameView.setSelectedFish(1); }
//update screen
gameView.invalidate();
}
});
}
};
public void pauseGame(View v){
String resume = "Resume";
String pause = "Pause";
if (!pauseFlag){
System.out.println("Turning timer of");
pauseFlag = true;
pauseButton.setText(resume);
movementTimer.cancel();
movementTimer=null;
}
else{
System.out.println("Starting timer again");
pauseFlag=false;
pauseButton.setText(pause);
try{
movementTimer = new Timer();
TimerTask newAnimationTask; //this did not work
createNewAnimationTask(newAnimationTask); //this did not work
movementTimer.scheduleAtFixedRate(animationTask, 0, animationPeriod); //here is where the error occurs
}
catch (Exception e){
System.out.println("ERROR: " + e);}
}
}
//attempted to make method that would generate new TimerTasks
public void createNewAnimationTask(TimerTask newAnimationTask){
newAnimationTask = new TimerTask() {
#Override
public void run(){
handler.post(new Runnable() {
#Override
public void run() {
System.out.println("Animation at work");
//here we set the animation
int selectedFish = gameView.getSelectedFish();
if (selectedFish==1){
gameView.setSelectedFish(0);}
if (selectedFish==0){
gameView.setSelectedFish(1); }
//update screen
gameView.invalidate();
}
});
}
};
}
}
What I'm wondering is how do I create a new TimerTask (like the "animationTask"), whenever I press the resume button?
I solved it. I removed all the TimerTask and just created everything in a function, like so:
public void createNewAnimationTask(){
movementTimer = new Timer();
TimerTask newAnimationTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
#Override
public void run() {
System.out.println("Animation at work");
//here we set the animation
int selectedFish = gameView.getSelectedFish();
if (selectedFish==1){
gameView.setSelectedFish(0);}
if (selectedFish==0){
gameView.setSelectedFish(1); }
//update screen
gameView.invalidate();
}
});
}
};
movementTimer.scheduleAtFixedRate(newAnimationTask, 0, animationPeriod);
}
Try adding the purge command also like;
movementTimer.cancel();
movementTimer.purge();

Java - Reusing Timer Object after calling cancel

I have an application in Java where I need to schedule a TimerTaskwhich will be executed after 500ms , however if a certain event occurs, I must reset the timer for this task (so that we must wait another 500ms for it to execute). I have a timer declared for the whole class. I use the following code:
public static void main(String[] args) {
if (curr_pck == my_pck) {
timer.cancel();
timer.purge();
timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
myTask();
}
}, 500);
}
}
public static void myTask() {
timer.cancel();
timer.purge();
timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
myTask();
}
}, 500);
//EXECUTE CODE WHICH ISN'T RELEVANT TO THE QUESTION
}
I know that if I use timer.cancel() I can't reuse the timer object, however I thought reinitialising it in the line timer = new Timer() should solve this issue. Is there any way around this?
EXCEPTION on line timer.schedule(new TimerTask() { inside myTask() function:
java.lang.IllegalStateException: Timer already cancelled.
Create a class Timerr with the appropriate methods. Then access it as if it were a normal timer.
public class Timerr
{
private Timer timer;
public Timerr()
{
timer = new Timer();
start();
}
public void start()
{
timer.schedule(new TimerTask()
{
#Override
public void run()
{
System.out.println("hi");
}
}, 500);
}
public void reset()
{
timer.cancel();
timer.purge();
start();
}
}
Create instance
private Timerr timer = new Timerr();
Do your reset
if(condition)
{
timerr.reset();
}
You may want to check out Java's Swing timer. It works somewhat differently and you may have to write an internal class or an actionlistener, but the Swing timer includes .stop() and .restart(), which seem like they would work better in your application.

Paho-Mqtt Periodic Publications approaches

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

android.view.WindowLeaked: Activity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView that was originally added here

I keep getting this error on this line of code and cannot figure out the root cause
closedialog.show();
I have tried putting a try/catch around it but the error still persists.
Runnable runnable = new Runnable() {
#Override
public void run() {
handler.post(new Runnable() { // This thread runs in the UI
#Override
public void run() {
try{
AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
alert.setTitle("Message");
alert.setMessage(alertMessage);
alert.setIcon(R.drawable.recharge_icon);
//alert.show();
final AlertDialog closedialog= alert.create();
closedialog.show();
final Timer timer2 = new Timer();
timer2.schedule(new TimerTask() {
public void run() {
closedialog.dismiss();
timer2.cancel(); //this will cancel the timer of the system
}
}, 8000); // the timer will count 5 seconds....
}catch(Exception ex){
ex.printStackTrace();
}
}
});
}
};
new Thread(runnable).start();
return
;
Please what could be wrong?

How to change android timer period?

I am writing simple game, where some action must accelerating during the process. The question is how to change timer's period?
timer = new Timer();
timerTask = new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
//
// I need to change timer's period here
//
}
});
}
};
timer.schedule(timerTask, 0, period);
Will be glad to hear any advices.
I assume that you are performing some logic within the run() method of the TimerTask.
I think a simpler way to go about this would be to use a Handler. This is possibly more idiomatic for Android:
private final Handler mHandler = new Handler();
private final Runnable mTask = new Runnable() {
#Override
public void run() {
// Do your logic.
// Now post again.
mHandler.postDelayed(mTask, /* choose a new delay period */);
}
};
public void init() {
delay = 1000L; // 1 second.
mHandler.postDelayed(mTask, delay);
}

Categories