8

I am using below code for scheduling a task in android but its not giving any results. Please advise on the same.

int delay = 5000; // delay for 5 sec.
int period = 1000; // repeat every sec.
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {

   public void run() {
      Toast.makeText(getApplicationContext(),"RUN!",Toast.LENGTH_SHORT).show();
   }

}, delay, period);
Janusz
  • 187,060
  • 113
  • 301
  • 369
Maneesh
  • 6,098
  • 5
  • 36
  • 55
  • 1
    For those who want to schedule service / activity start or broadcast, take a look at [AlarmManager](http://developer.android.com/reference/android/app/AlarmManager.html) – Alexander Malakhov Aug 14 '13 at 02:44

2 Answers2

17

TimerTasks are not ideal to use in an android environment because they're not context-aware. If your context goes away, the TimerTask will still wait patiently in the background, eventually firing and potentially crashing your app because its activity was previously finished. Or, it may keep references to your activity around after it's been closed, preventing it from being garbage collected and potentially making your app run out of memory.

Instead, use postDelayed(), which will automatically cancel the task when the activity is shut down.

final int delay = 5000;
final int period = 1000;
final Runnable r = new Runnable() {
    public void run() {
        Toast.makeText(getApplicationContext(),"RUN!",Toast.LENGTH_SHORT).show();
        postDelayed(this, period);
    }
};

postDelayed(r, delay);

By the way, if you ever need to cancel your task manually, you can use removeCallbacks(r) where r is the runnable you posted previously.

Daniel Kreiseder
  • 12,135
  • 9
  • 38
  • 59
emmby
  • 99,783
  • 65
  • 191
  • 249
4

I got the answer as per below code:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    Timer timer = new Timer();

    timer.schedule(new ScheduledTaskWithHandeler(), 5000);

}

final Handler handler = new Handler() {

   public void handleMessage(Message msg) {
       Toast.makeText(getApplicationContext(), "Run!",
           Toast.LENGTH_SHORT).show();
   }
};

class ScheduledTaskWithHandeler extends TimerTask {

    @Override
    public void run() {
        handler.sendEmptyMessage(0);
    }
}
frogatto
  • 28,539
  • 11
  • 83
  • 129
Maneesh
  • 6,098
  • 5
  • 36
  • 55
  • 3
    Please just call `postDelayed()` on any `View`. No `Timer`, no `TimerTask`, no extra thread, and no need for a `Handler`. – CommonsWare Nov 14 '10 at 23:32
  • @CommonsWare What if when you need a repeat timer ?? – StarDust Nov 16 '13 at 03:01
  • 1
    @StarDust: Call `postDelayed()` again, as part of the work done by the `Runnable` you scheduled with the first `postDelayed()`: https://github.com/commonsguy/cw-omnibus/tree/master/Threads/PostDelayed – CommonsWare Nov 16 '13 at 03:03